Vue自定义指令

307 阅读1分钟
一、定义语法:

(1)局部指令:

new Vue({
     directives:{指令名:配置对象}
})

或者

new Vue({
    directives:{指令名:回调函数}
})

(2)全局指令:
Vue.directive(指令名,配置对象) 或者 Vue.directive(指令名,回调函数)

二、配置对象中常用的3个回调:

        (1).bind:指令与元素成功绑定时调用

        (2).inserted:指令所在元素被插入页面时调用

        (3).update:指令所在模板结构被重新解析时调用

注意:

  1. 指令定义是不加v- 但使用时要加v-
  2. 指令名如果是多个单词,要使用kebab-case(短横线隔开)命名方式,不要用camelCase(驼峰命名法)命名
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.js"></script>
</head>
<body>
    <!-- 需求1:定义一个v-big指令,和v-text功能类似,但会把绑定的数值放大10倍
    需求2:定义一个v-fbind指令,和v-bind功能类似,但可以让其所绑定的input元素默认获取焦点 -->
    <div id="root">
        <h2>当前的n值是:<span v-text="n"></span></h2>
        <h2>放大10倍后的n值是:<span v-big="n"></span></h2>
        <button @click="n++">点我n+1</button>
        <hr>
        <input type="text" v-fbind:value="n">
    </div>
    <script>
        Vue.config.productionTip = false
        // 方法一 全局指令
        Vue.directive('fbind',{
                    // 指令与元素成功绑定时
                    bind(element, binding) {
                        element.value = binding.value
                        // console.log(this);     注意此处的this是window
                    },
                    // 指令所在元素被插入页面时
                    inserted(element, binding) {
                        element.focus()
                    },
                    // 指令所在的模板被重新解析时
                    update(element, binding) {
                        element.value = binding.value
                    }
                })
        new Vue({
            el: '#root',
            data: {
                n: 1
            },
            // 方法二 局部指令
            directives: {
                // big函数何时会被调用?
                //     1.指令与元素成功绑定时(一上来)
                //     2.指令所在的模板被重新解析时
                big(element, binding) {
                    element.innerText = binding.value * 10
                },
                fbind: {
                    // 指令与元素成功绑定时
                    bind(element, binding) {
                        element.value = binding.value
                        // console.log(this);     注意此处的this是window
                    },
                    // 指令所在元素被插入页面时
                    inserted(element, binding) {
                        element.focus()
                    },
                    // 指令所在的模板被重新解析时
                    update(element, binding) {
                        element.value = binding.value
                    }
                }
            },
        })
    </script>
</body>
</html>

自定义指令.gif