Vue之自定义指令的创建和使用

Vue之自定义指令的创建和使用

Vue自带的指令很多,如v-for/v-if/v-else/v-else-if/v-model/v-bind…

但是这些指令都是比较偏向于工具化,有些时候在实现具体业务逻辑的时候,发现不够用,那如何来自定义指令?

1.自定义指令

<body>
    <div id="container">
        <p>{{msg}}</p>
        <!-- 准备实现需求:
        在h1标签上面,加上一个按钮,当点击按钮时候,对count实现一次自增操作,当count等于5的时候,在控制台输出’it is a test‘ -->
        <button @click="handleClick">clickMe</button>
        <h1 v-if="count < 6" v-change="count">it is a custom directive</h1>
    </div>

    <script>
        //directive
        new Vue({
            el: "#container",
            data: {
                msg: '麻子',
                count: 0
            },
            methods: {
                handleClick: function () {
                    //按钮单击,count自增
                    this.count++;
                }
            },
            directives: {
                change: {
                    bind: function (el, bindings) {
                        console.log('指令已经绑定到元素了');
                        console.log(el);
                        console.log(bindings);
                        //准备将传递来的参数显示在调用该指令的元素的innerHTML
                        el.innerHTML = bindings.value;
                    },
                    update: function (el, bindings) {
                        console.log("指令的数据有所变化");
                        console.log(el);
                        console.log(bindings);
                        el.innerHTML = bindings.value;
                        if (bindings.value == 5) {
                            console.log("it is a test");
                        }
                    },
                    unbind: function () {
                        console.log("解除绑定了");
                    }
                }
            }
        })
    </script>
</body>

2.使用自定义指令

如:v-change

3 .注意

在自定义指令时,在指令对应的配置对象中有了3个处理函数指令对应的操作:

bind:指令在绑定到元素要执行的操作

update:如果在调用指令时候,传了参数,当参数变化的时候就会执行update所指定的方法

ubind:解绑要执行的操作

注意事项:建议在给指令的命名采用小驼峰式的命名方式:changeBackgroundColor
在使用的时候,采用烤串式写法:v-change-background-color

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值