关于网友提出的“ (vue.js)怎样写这个指令,让它看起来像是一个整体?”问题疑问,本网通过在网上对“ (vue.js)怎样写这个指令,让它看起来像是一个整体?”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:
问题: (vue.js)怎样写这个指令,让它看起来像是一个整体?
描述:
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
,jrs看球网直播吧_低调看直播体育app软件下载_低调看体育直播里边明明写着可以用这两种方法,但是使用后者总报上边那个错(设置不存在的路径错误)。
解决方案1:实际上如果你要建立一个 全局
的指令的话,就只能这样做,可以放在实例里面,但就不是全局了,而是当前实例底下才有作用,例如你放在 Component
底下,那就只有该 Component
底下才能用。
以上介绍了“ (vue.js)怎样写这个指令,让它看起来像是一个整体?”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/3112414.html