全局
/**
* 全局指令 v-ff
* Vue.directive('ff',{})
* 指令使用比较频繁的情况下使用全局
*
* 局部指令
* 只使用一次 或少量次数的指令 使用局部
*/
Vue.directive('ff', {
// 当把指令与el绑定在一起的时候触发
bind(el, binding, vnode) {
// 当指令绑定到元素上时触发
// 是获取到binding的值
el.value = binding.value
// 绑定的值在组件中的变量名称
const name = binding.expression
// 给元素添加 原生事件获取到 元素的内容变化
// vnode.context 你的指令所在的组件
el.addEventListener('input', function() {
// 通过vnode的context修改组件中对应的变量
vnode.context[name] = el.value
})
},
inserted(el, binding) {
// 表示该指令所在的元素已经插入到dom了
// el.focus()
},
update(el, binding) {
// 当指令绑定的组件内部数据发生改变时触发该钩子函数
el.value = binding.value
}
})
局部
directives: { //directives 自定义指令
focus: { // v-focus
bind(el, binding, vnode, oldVnode) {
// v-focus绑定到元素或组件上时触发
// console.log('bind')
// html 原生元素对象
// el.focus()
// 在这里 指令所在的元素还没有被插入到dom所以 元素一些动态操作是不能实现的
el.style.background = 'red';
// console.log(binding)
},
inserted(el, binding, vnode, oldVnode) {
// 当指令所在的元素插入到dom时 触发这个钩子
// console.log('inserted')
el.focus()
},
update(el, binding, vnode, oldVnode) {
// console.log('update')
}
},
批量导入
Vue.use((Vue) => {
((requireContext) => {
const arr = requireContext.keys().map(requireContext);
(arr || []).forEach((directive) => {
directive = directive.__esModule && directive.default ? directive.default : directive;
Object.keys(directive).forEach((key) => {
Vue.directive(key, directive[key]);
});
});
})(require.context('../directives', false, /^\.\/.*\.js$/));
});
钩子函数的参数 (即 el
、binding
、vnode
和 oldVnode
),除了 el
之外,其它参数都应该是只读的,切勿进行修改。如果需要在钩子之间共享数据,建议通过元素的 dataset
来进行