params
定义对象中可以接受一个 params 数组,Vue.js 编译器将自动提取自定义指令绑定元素 上的这些属性。例如:
<div v-my-advance-directive a="paramA"></div>
Vue.directive('my-advance-directive', {
params : ['a'],
bind : function() {
console.log('params', this.params);
}
});
deep
当自定义指令作用于一个对象上时,我们可以使用 deep 选项来监听对象内部发生的变 化。例如:
<div v-my-deep-directive="obj"></div>
<div v-my-nodeep-directive="obj"></div>
Vue.directive('my-deep-directive', {
deep : true,
update : function(newValue, oldValue) {
console.log('deep', newValue.a.b);
}
});
Vue.directive('my-nodeep-directive', {
update : function(newValue, oldValue) {
console.log('deep', newValue.a.b);
}
});
var vm = new Vue({
el : '#app',
data : {
obj:{
a:{
b : 'inner'
}
}
}
})
twoWay
在自定义指令中,如果需要向 Vue 实例写回数据,就需要在定义对象中使用 twoWay:true, 这样可以在指令中使用 this.set(value) 来写回数据。
<input type="text" v-my-twoway-directive="param" / >
Vue.directive('my-twoway-directive', {
twoWay : true,
bind : function() {
this.handler = function () {
console.log('value changed: ', this.el.value);
this.set(this.el.value)
}.bind(this)
this.el.addEventListener('input', this.handler) },
unbind: function () {
this.el.removeEventListener('input', this.handler) }
});
var vm = new Vue({
el : '#app',
data : {
param : 'first',
}
});
acceptStatement
选项 acceptStatement:true 可以允许自定义指令接受内联语句,同时 update 函数接收 的值是一个函数,在调用该函数时,它将在所属实例作用域内运行。
<div v-my-directive="i++"></div>
Vue.directive('my-directive', {
acceptStatement: true,
update: function (fn) {
}
})
var vm = new Vue({
el : '#app',
data : {
i : 0
}
});
terminal
选项 terminal 的作用是阻止 Vue.js 遍历这个元素及其内部元素,并由该指令本身去编译 绑定元素及其内部元素。内置的指令 v-if 和 v-for 都是 terminal 指令。
使用 terminal 选项是一个相对较为复杂的过程,你需要对 Vue.js 的编译过程有一定的了 解,这里借助官网的一个例子来大致说明如何使用 terminal。
priority
选项 priority 即为指定指令的优先级。普通指令默认是 1000,termial 指令默认为 2000。同一元素上优先级高的指令会比其他指令处理得早一些,相同优先级则按出现顺序依 次处理。以下为内置指令优先级顺序:
export const ON = 700
export const MODEL = 800
export const BIND = 850
export const TRANSITION = 1100
export const EL = 1500
export const COMPONENT = 1500
export const PARTIAL = 1750
export const IF = 2100
export const FOR = 2200
export const SLOT = 2300