美文网首页vue集锦
Vue.directive指令(自定义指令)

Vue.directive指令(自定义指令)

作者: 幸运三片叶 | 来源:发表于2019-07-18 09:16 被阅读2次

定义方式

  • html页面定义
Vue.directive("hello",function(el,binding,vnode){
       el.style["color"]= binding.value;
    })
  • 全局定义
Vue.directive('hello', {
    inserted(el) {
        console.log(el);
    }
})
  • 局部定义
var app = new Vue({
    el: '#app',
    data: {    
    },
    // 创建指令(可以多个)
    directives: {
        // 指令名称
        hello: {
            inserted(el) {
                // 指令中第一个参数是当前使用指令的DOM
                console.log(el);
                console.log(arguments);
                // 对DOM进行操作
                el.style.width = '200px';
                el.style.height = '200px';
                el.style.background = '#000';
            }
        }
    }
})

参数(每个指令都含有这三个参数)

  • el : 指令所绑定的元素,可以用来直接操作DOM
  • binding: 一个对象,包含指令的很多信息
  • vnode: VUE编译生成的虚拟节点

生命周期

  • bind 只调用一次,指令第一次绑定到元素时候调用,用这个钩子可以定义一个绑定时执行一次的初始化动作。
  • inserted:被绑定的元素插入父节点的时候调用(父节点存在即可调用,不必存在document中)
  • update: 被绑定与元素所在模板更新时调用,而且无论绑定值是否有变化,通过比较更新前后的绑定值,忽略不必要的模板更新
  • componentUpdate :被绑定的元素所在模板完成一次更新更新周期的时候调用
  • unbind: 只调用一次,指令元素解绑的时候调用
Vue.directive("hello",{
        bind:function(el,bingind,vnode){
            el.style["color"] = bingind.value;
            console.log("1-bind");
            console.log(el.parentNode);
        },
        inserted:function(){
            console.log("2-insert");
            console.log(el.parentNode);
        },
        update:function(){
            console.log("3-update");
        },
        componentUpdated:function(){
            console.log('4 - componentUpdated');
        },
        unbind:function(){
            console.log('5 - unbind');
        }
    })

相关文章

网友评论

    本文标题:Vue.directive指令(自定义指令)

    本文链接:https://www.haomeiwen.com/subject/idjclctx.html