自定义指令插件
创建/utils/directives.js文档
import Vue from 'vue'
export default {
install () {
// 创建全局自定义指令
Vue.directive('autofocus', {
// 指令所在标签"首次"被插入到真实DOM时会执行的回调,传回来的参数为具体的原生DOM标签
inserted (el) {
if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
el.focus()
} else {
// 指令在van-search组件身上, 获取的是组件根标签div, 而input在组建根标签内
// querySelector:查询选择器
// 获取的标签对象.querySelector('选择器名') : 在 获取的标签对象 中 查询并获取 满足查询选择器条件的 第一个选择器
// el = el.querySelector('input')
// el.focus()
const inp = el.querySelector('input')
const textArea = el.querySelector('textarea')
// 如果找到了
if (inp || textArea) {
// 短路语法
inp && inp.focus()
textArea && textArea.focus()
} else {
// 本身也不是, 子标签里也没有
console.error('请把v-inpfocus用在输入框标签上')
}
}
},
// 当前绑定指令的元素上的数据更新的时候触发,
// 用来解决再次打开时,不能自动聚焦的问题
update (el) {
if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
el.focus()
} else {
const inp = el.querySelector('input')
const textArea = el.querySelector('textarea')
// 如果找到了
if (inp || textArea) {
// 短路语法
inp && inp.focus()
textArea && textArea.focus()
} else {
// 本身也不是, 子标签里也没有
console.error('请把v-inpfocus用在输入框标签上')
}
}
}
})
}
}
在main.js导入并注册插件
import diretivesObj from '@/utils/directives'
Vue.use(diretivesObj)

浙公网安备 33010602011771号