- {{email}}
Vue.directive('DirEmail',{
bind:function(){},
update:function(newValue){
if(!newValue) return;
var needAt=this.modifiers.needat || false,
emails=[],
at=newValue.indexOf('@'),
user='';
if(needAt && !~at){
this.vm.emails=emails;
return false;
}
if(~at){
this.vm.host=newValue.substr(at);
user=newValue.substr(0,at);
}
else{
this.vm.host='';
user=newValue;
}
for(var n in hosts){
emails.push(user+'@'+hosts[n]);
}
this.vm.emails=emails;
},
unbind:function(){}
})
var hosts=['126.com','163.com','qq.com','yahoo.com','yahoo.com.cn'];
new Vue({
el:"#EmailInput",
data:function(){
return {
emailAddress:'',
host:'',
emails:[]
}
}
})
现在指令跟实例是分开的,但是逻辑上,它们应该是一个整体才对,应该怎么写才能把它们两个整合到一起呢?是把指令里边的东西,写在实例里边还是怎么样呢?
我把实例中的data移动到directive里边,刷新没问题,往里一打值就报错。我在bind钩子上使用this.vm.$set也是报错,都报
Vue warn: You are setting a non-existent path "emailAddress" on a vm instance. Consider pre-initializing the property with the "data" option for more reliable reactivity and better performance.
好像是说无法在实例上设置不存在的数据。
我找到方法了,是在directive的bind中使用Vue.set(),把属性设置进去。但是为什么不能用this.vm.$set,教程里边明明写着可以用这两种方法,但是使用后者总报上边那个错(设置不存在的路径错误)。
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
實際上如果你要建立一個
全局的指令的話,就只能這樣做,可以放在實例裡面,但就不是全局了,而是當前實例底下才有作用,例如你放在Component底下,那就只有該Component底下才能用。