一、vue2中实现v-focus
1、在main.js中添加如下代码
/** * 定义全局的输入框获取焦点指令 */ Vue.directive('focus', { inserted: function (el) { el.querySelector('input').focus() },
2、在代码中加上v-focus
<el-form-item label="数据源用户名:"> <el-input v-model.trim="listQuery.username" clearable v-focus></el-input> </el-form-item>
效果如下:
二、vue3中实现v-focus
script
<script> import {ref, onMounted} from 'vue' export default { name: "LeeDirectives", setup(){ const input =ref(null) onMounted(()=>{ input.value.focus() }) return { input } } } </script>
template
<el-input v-model.trim="listQuery.title" clearable type="text" ref="input"/>