Skip to content

定义语句

局部指令

  1. 方法 1

    javascript
    new Vue({
    	directives: { 指令名:配置对象 }
    })
  2. 方法 2

    javascript
    new Vue({
        directives: {
            指令名(){
                
            }
        }
    })

全局指令

  1. 方法 1

    javascript
    Vue.directive(指令名,配置对象)
  2. 方法 2

    javascript
    Vue.directive(指令名,回调函数)

配置对象中常用的 3 个回调函数

  1. bind:指令与元素成功绑定时调用。
  2. inserted:指令所在元素被插入到页面时调用。
  3. update:指令所在模板结构被重新解析时调用。

注意事项

  1. 指令在定义时不加 v-,但在使用时必须加 v-
  2. 指令名如果是多个单词,要是用 kebab-case 命名方式,不要使用 camelCase 命名。

代码

需求一

  1. 需求:通过点击按钮,把这个值及这个值放大10倍后的值渲染到页面上。

  2. 代码

    html
    <body>
        <div id="root">
            <h2>当前 n 的值为:{{ n }}</h2>
            <h2>放大 10 倍后 n 的值为:<span v-big="n"></span></h2>
            <button @click="n++">n++</button>
        </div>
        <script>
            new Vue({
                el: '#root',
                data: {
                    n: 1
                },
                directives: {
                    big(element,binding){
                        element.innerText = binding.value * 10;
                        console.log(element,binding);
                    }
                }
            })
        </script>
    </body>

需求二

  1. 需求:点击按钮把变量值绑定在 input 标签上,初次加载和更新数据是让 input 自动获取焦点。

  2. 代码

    html
    <body>
        <div id="root">
            <h2>当前 n 的值为:{{ n }}</h2>
            <input type="text" v-fbind:value="n">
            <button @click="n++">n++</button>
        </div>
        <script>
            new Vue({
                el: '#root',
                data: {
                    n: 1
                },
                directives: {
                    fbind: {
                        bind (el,bi) {
                            el.value = bi.value;
                        },
                        inserted (el,bi) {
                            el.focus();
                        },
                        update (el,bi) {
                            el.value = bi.value;
                            el.focus();
                        },
                    }
                }
            })
        </script>
    </body>

需求三

  1. 需求:用全局指令实现需求一

  2. 代码

    html
    <body>
        <div id="root">
            <h2>当前 n 的值为:{{ n }}</h2>
            <h2>放大 10 倍后 n 的值为:<span v-big="n"></span></h2>
            <button @click="n++">n++</button>
        </div>
        <script>
            Vue.directive('big',function(element,binding){
                element.innerText = binding.value * 10;
            })
            new Vue({
                el: '#root',
                data: {
                    n: 1,
                },
            })
        </script>
    </body>

基于 MIT 许可发布