vue 自定义指令

自定义指令

当指令不满足需求时,可以自定义指令,语法如下:

Vue.directive('focus',{
    inserted: function(el){
        //el表示指令所绑定的元素
        el.focus()
    }
})

使用方法和其他指令一样

<input type="text" v-focus>

带参数的自定义指令

定义好指令,将数据定义好,再通过输入框应用

Vue.directive('color', {
      bind: function(el, binding){
        // 根据指令的参数设置背景色
        // console.log(binding.value.color)
        el.style.backgroundColor = binding.value.color;
      }
    });
<input type="text" v-color='msg'>
var vm = new Vue({
      el: '#app',
      data: {
        msg: {
          color: 'blue'
        }
      }
    });

此时,当实例中数据msg改变,那么页面中输入框中的背景颜色也会改变。

局部定义指令

添加在Vue实例组件中,这时候该指令只能在Vue定义的实例中使用

directives: {
        focus: {
          //指令的定义
          inserted: function(el) {
            el.focus();
          }
        }
      }

 

posted @ 2020-12-13 20:35  黎沐不吃香菜  阅读(96)  评论(0)    收藏  举报