Vue 自定义指令

2019-08-29  本文已影响0人  养乐多__

一、自定义指令基本用法

Vue 中已有的指令往往不能满足我们开发过程中的全部要求,因此有时我们需要自定义一些指令来实现某些特有的功能。
和组件类似,自定义指令也分为全局注册和局部注册,二者区别就是把component 换成了 directive。例:

Vue.directive('指令名称', {
  // 指令的选项
});

二、钩子函数

Vue 提供了几个钩子函数作为自定义指令的选项:

三、钩子函数的参数

<div id="app">
    获取焦点:<input type="text" v-focus> <br>
</div>
<script>
    // 需求:input 框在初始化时就获取焦点
    Vue.directive('focus', {
        // 指令的选项
        inserted: function(el){  // 插入到父节点时就调用
            el.focus()
        }
    });
    var app = new Vue({
        el: "#app", 
    })
</script>
<div id="app">
    <!-- 自定义指令 -->
    <div v-apple:pear.a.b.c="red"></div>
</div>
<script>
    Vue.directive('apple', {
        bind: function(el, binding){
            el.innerHTML =
            'name' + ' --- ' + binding.name + '<br>' +
            'value' + ' --- ' + binding.value + '<br>' +
            'expression' + ' --- ' + binding.expression + '<br>' +
            'argument' + ' --- ' + binding.arg + '<br>' +
            'modifiers' + ' --- ' + JSON.stringify(binding.modifiers) + '<br>'
        }
    });
    var app = new Vue({
        el: "#app", 
        data: {
            red: '我是自定义指令所绑定的值'
        }
    })
</script>
运行结果为: 自定义指令 --- binding
<div id="app">
    <div v-apple:pear.a.b.c="red"></div>
</div>
<script>
    Vue.directive('apple', {
        bind: function(el, binding, vnode){
            var keys = [];
            for(var key in vnode){
                keys.push(key)
            };
            el.innerHTML =
                'vnode 中的 keys:' + keys.join("--") + '<br>'
        }
    });
    var app = new Vue({
        el: "#app", 
        data: {
            red: '我是自定义指令所绑定的值'
        }
    })
</script>
运行结果为: 自定义指令 --- vnode
上一篇下一篇

猜你喜欢

热点阅读