<div id="app">
<input type="text" v-model="cur">
<div v-my-directive="cur">hello</div>
</div>
指令中的事件(默认为update事件)
Vue.directive('my-directive',{
bind(){
this.handle=()=>{
alert(100);
};
this.el.addEventListener('click',this.handle)
},
update(newVal,oldVal){
console.log(newVal,oldVal);
setTimeout(()=>{
this.unbind();
},2000);
},
unbind(){
this.el.removeEventListener('click',this.handle)
}
});
var vm = new Vue({
el:'#app',
data:{cur:'index'},
});
<div v-my-directive:hello.a.e="ee"></div>
Vue.directive('my-directive',
function () {
console.log(this.el);//当前元素
console.log(this.vm);//当前scope
console.log(this.expression);//ee表达式
console.log(this.arg);//hello参数
console.log(this.name);//当前指令的名字
console.log(this.modifiers);//修饰符{e,a}
console.log(this.descriptor);//当前指令的描述
}
)
var vm = new Vue({
el:'#app',
data:{cur:'index'},
});
<div id="app">
<my-directive>my world</my-directive>
</div>
通过元素创建指令
Vue.elementDirective('my-directive', {
bind: function () {
this.el.innerHTML = 'hello world';
}
});
var vm = new Vue({
el:'#app'
})
<input type="text" v-model="message">
<my-directive :a="message">my world</my-directive>
监听动态属性值变化
Vue.elementDirective('my-directive', {
params:['a'],
bind: function () {
console.log(this.params.a);
this.el.innerHTML = 'hello world';
},
paramWatchers:{
a:function (old,newVal) {
console.log(old,newVal);
}
}
});
var vm = new Vue({
el:'#app',
data:{
message:'hello'
}
})
<input type="text" v-model="message.hello">
<div v-my-directive="message"></div>
Vue.directive('my-directive', {
params:['a'],
deep:true,
update:function (obj) {
console.log(obj);
}
});
var vm = new Vue({
el:'#app',
data:{
message:{
hello:'world'
}
}
})
<div id="app">
<input type="text" v-my-directive="bug">
{{bug}}
</div>
通过set方法写回vm中
Vue.directive('my-directive',{
twoWay:true,
bind: function () {
this.handle= function () {
this.set(this.el.value);
}.bind(this);
this.el.addEventListener('input',this.handle,false)
}
});
var vm = new Vue({
el:'#app',
data:{
message:{
hello:'world'
}
}
})
<input type="text" v-my-directive="bug=(124==124?0:1)">
{{bug}}
将参数转化为函数
Vue.directive('my-directive',{
twoWay:true,
acceptStatement:true,
update: function (fn ) {
fn()
}
});
var vm = new Vue({
el:'#app',
data:{}
})
抽取公有逻辑
var mixins = {
created: function () {
this.hello();
},
methods:{
hello: function () {
console.log('from mixinHello');
}
}
};
var com = Vue.component('parent',{
mixins:[mixins],
created: function () {
console.log('from my');
},
methods:{
hello: function () {
console.log('from myHello');
}
}
});
new com;
全局注册混合(慎用)
Vue.mixin({
created: function () {
var v = this.$options.dd;
console.log(v);
}
})
new Vue({
dd: 'hello!'
})
因为它影响到每个创建的 Vue 实例,包括第三方组件。在大多数情况下,它应当只用于自定义选项。