自定义指令

243 阅读1分钟
  1. 全局指令
<body>
<div id="app">
    <input type="text" v-focus>
</div>

<script>
    
    Vue.directive('focus',{
        inserted: function (el) {
            el.focus();
        }
    })
    
    new Vue({
        el:"#app"
    })

    
</script>
</body>
  1. 局部指令
<body>
<div id="app">
    <input type="text" v-focus>
</div>

<script>

    new Vue({
        el:"#app",
        directives: {
            focus: {
                inserted: function (el) {
                    el.focus();
                }
            }
        }
    })

    
</script>
</body>
  1. 常用钩子函数
    1. 函数

      1. bind: 绑定时候调用
      2. inserted: 插入到父节点时候调用
    2. 参数

      1. el: 元素,可以直接操作DOM
      2. binding: 对象
        1. name: 就是不包括v-后面的部分
        2. value: 就是双引号中的部分的真实值
        3. expression: 表达式就是双引号中的部分
        4. arg: 参数,就是:后边的部分
        5. modifiers: 修饰,就是点后面的部分
    3. 示例代码

      1. bind钩子函数
         <body>
           <div id="app">
               <p v-runoob:hello.a.b="message"></p>
           
           </div>
           
           <script>
           
               new Vue({
                   el:"#app",
                   data:{
                       message:"fdsa"
                   },
                   directives:{
                       runoob:{
                           bind: function (el,binding) {
                               el.innerHTML = 'name:' + binding.name + '<br/>' +
                                              'arg:' + binding.arg + '<br/>' +
                                              'modifiers:' + JSON.stringify(binding.modifiers) + '<br/>' +
                                              'expression:' + binding.expression + '<br/>' +
                                              'value:' + binding.value;
                           }
                       }
                   }
           
               })
           
           </script>
           </body>  
      
      1. 简写形式
      <body>
      <div id="app">
          <p v-runoob:hello.a.b="message"></p>
      
      </div>
      
      <script>
      
          Vue.directive('runoob',function (el, binding) {
              el.innerHTML = 'name:' + binding.name + '<br/>' +
                  'arg:' + binding.arg + '<br/>' +
                  'modifiers:' + JSON.stringify(binding.modifiers) + '<br/>' +
                  'expression:' + binding.expression + '<br/>' +
                  'value:' + binding.value;
          })
      
          new Vue({
              el:"#app",
              data:{
                  message:"fdsa"
              }
      
          })
      
      </script>
      </body>
      
  2. 钩子函数的值可以是任意的合法的js的表达式
<body>
<div id="app">
    <p v-runoob="{ color: 'green', text: '菜鸟教程!' }"></p>

</div>

<script>

    Vue.directive('runoob',function (el, binding) {
        el.innerHTML = 'color:' + binding.value.color + '<br/>' +
                'text:' + binding.value.text;
    })

    new Vue({
        el:"#app"
    })

</script>
</body>