面试题系列---【Vue中的自定义指令和使用方式】

自定义指令
当Vue中的核心内置指令不能够满足我们的需求时,我们可以定制自定义的指令用来满足开发的需求。

1、全局自定义指令
(1)定义全局自定义指令
以下就是一个自定义指令让文本框获取焦点的实例:

//自定义全局的指令
Vue.directive('focus', {
//第一个参数永远是el,表示原生的js对象
bind: function (el) { //当指令绑定到元素上的时候,会立即执行bind函数,只执行一次,此时元素还没有插入到DOM中,focus聚焦此时不会生效
el.focus()
},
inserted: function (el) { //当元素插入到DOM中的时候,会执行inserted函数,只执行一次
el.focus()
},
updated: function () { //当VNode的时候,会执行updated函数,可能出发多次
}
});

(2)使用全局自定义指令

<input type="text" class="form-control" v-model="keywords" v-focus">

2、私有自定义指令(组件内定义指令)
(1)和私有自定义过滤器类似,也是将作为和methods平级的属性定义在VM的实例中

directives: {
'fontweight': {
bind: function (el, bingding) {
el.style.fontWeight = bingding.value;
}
},
'fontsize': function (el, bingding) { //这个function等同于把代码写到了bind和update中去
el.style.fontSize = parseInt(bingding.value) + 'px';
}
}

(2)在dom中使用该指令

 <div id="app2" v-color="'pink'" v-fontweight="200" v-fontsize="20">
    <p>{{date | dateFormat}}</p>
 </div>
原文地址:https://www.cnblogs.com/chenhaiyun/p/15000593.html