<div class="edit-tag" v-for="tag in dynamicTags" :key="tag.id">
<el-input
v-model="tag.tagName"
ref="tagEditInput"
class="input-edit-tag"
v-if="tag.isEditTag"
:autofocus="true"
@blur="hideInput(tag)"
/>
<el-tag
v-else
:class="{ tag__select: isActive, tag__item: true }"
:disable-transitions="false"
:title="tag.name"
@close="handleClose(tag)"
>
<span class="tagNameContainer">{{ tag.name }}</span>
<i class="el-icon-edit" @click.stop="showInput(tag)" />
<i class="el-icon-close" />
</el-tag>
</div>
this.$refs.tagEditInput[0].$el.querySelector('input').focus();
全局注册自定义指令
在vue-cli3中main.js中自定义指令
import Vue from 'vue'
import App from './App.vue'
import router from '@/router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import '@/assets/css/base.less'
import '@/assets/font-icon/iconfont.css'
// vuex store
import store from '@/store/index'
Vue.use(ElementUI);
Vue.config.productionTip = false
Vue.directive('focus', {
inserted: function(el){
console.log(el)
// el表示指令所绑定的元素
el.querySelector('input').focus()
}
});
new Vue({
el: '#app',
router,
store,
render: h => h(App),
}).$mount('#app')
Vue.directive('focus', {
inserted: function(el){
console.log(el)
// el表示指令所绑定的元素
el.querySelector('input').focus()
}
});
在组件中使用
<div class="edit-tag" v-for="tag in dynamicTags" :key="tag.id">
<el-input
v-model="tag.tagName"
v-focus
ref="tagEditInput"
class="input-edit-tag"
v-if="tag.isEditTag"
@blur="hideInput(tag)"
/>
<el-tag
v-else
:class="{ tag__select: isActive, tag__item: true }"
:disable-transitions="false"
:title="tag.name"
@close="handleClose(tag)"
>
<span class="tagNameContainer">{{ tag.name }}</span>
<i class="el-icon-edit" @click.stop="showInput(tag)" />
<i class="el-icon-close" />
</el-tag>
</div>
本文介绍了如何在Vue项目中使用自定义指令`focus`,以便在Element UI的`el-input`上实现点击后立即获取焦点。通过在全局注册并应用该指令,简化了组件内的焦点操作,并展示了如何在`v-for`循环中的编辑和选中标签元素中应用此功能。
471

被折叠的 条评论
为什么被折叠?



