自定义指令的注册

65 阅读1分钟

有些dom操作需要多次使用,因此可以封装成自定义指令,提高复用性

1.全局注册

在main.js中注册

Vue.directive('指令名', {  //通过directive设置自定义指令
    //el代表该指令绑定的DOM元素,binding代表指令值,inserted是钩子函数,意思是插入,元素插入后执行
    inserted(el, binding) {       
        语句
    },
    update() {            //update也是钩子函数,在该指令的值变化时自动执行
        语句               
    }
})

2.局部注册

export default {
    directive: {
        指令名: {
            inserted(el) {
                语句
            }
        }
    }
}