vue 自定义指令

自定义指令

Vue.directive("指令名",{});
  • Vue.directive内部钩子函数
    1). bind(){} // 绑定元素时执行,只执行一次(常用)
    2). inserted(){} // 当被绑定元素插入到dom时执行
    3). update(){} // 当被绑定元素更新时执行
    4). componentUpdated(){} // 被绑定元素模版完成一次周期更新时执行
    5). unbind(){} // 当被绑定元素解除时执行

  • Vue.directive钩子函数参数介绍
    1). el // 返回被绑定元素的dom对象
    2). binding // 返回绑定元素的各种参数object
    ps:binding实例方法:

        // 钩子函数的参数介绍
        html调用方法:<p v-world:foo.add.dele="hehe">{{msg}}</p>

        Vue.directive("world",{
            bind(el, binding){
                // console.log(el);        //  el:返回被绑定元素的dom对象
                console.log(binding);
                /*   binding 返回的各种参数
                    
                    {
                        name: "world",      // 返回自定义指令的名字
                        rawName: "v-world:foo.add.dele", // 返回自定义指令的调用
                        value: "eeeeeeeeee",        // 返回指令绑定的值
                        expression: "hehe",         // 返回指令绑定的值的名字
                        arg: "foo",         // 返回调用时参数foo的名字
                        …
                    }
                    arg: "foo"
                    expression: "hehe"
                    add: true       // 指令的修饰符
                    dele: true
                    name: "world"   // 指令的修饰符
                    rawName: "v-world:foo.add.dele"
                    value: "eeeeeeeeee" 
                */
            }
        })
  • Vue.directive第二种使用方法,直接传入一个函数,但是只会执行bing()和update()
        html调用:<p v-onefn>{{msg}}</p>
        // 传入一个函数的方法   只会执行bing()和update()钩子函数,另外指令名还不能驼峰式写法
        Vue.directive("onefn",function(){       
            alert("directive传入一个函数的方法")        
        })
  • Vue.directive局部写法
    局部写法式写在vue实例内部,而且是写为:directives,多加了一个s
    局部用法实例:
    html调用:<input type="text" v-model="msg" v-inpfocus>
    var vm = new Vue({
        el: "#app",
        data:{
            msg:"hello vue!",
        },
        methods:{
            
        },
        directives:{         // 自定义指令局部写法,局部写法记得加s为directives 全局为 Vue.directive
            inpfocus:{
                inserted(el){
                    el.focus();
                }
            }
        }
    });
自定义指令拖拽练习

点击demo查看

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值