我正在使用计算出的vueJs为我的组件创建选项,如下所示:
computed:{
fileOptions() {
let fileOptions = [
{
event:'event',
name:'Abcd',
disabled://based upon some condition,
display://based upon some condition
},
{
event://based upon some condition,
name:'Open Presentation',
disabled://based upon some condition,
display://based upon some condition
},
]
}
}
事件,禁用和显示属性基于多种条件。
一种方法是使用三元运算符
disabled:this.state.libraryActive=='presentations'?false:true
但是,对于一个条件来说很容易,但是对于多个条件来说却变得困难。
有什么建议吗?
答案 0 :(得分:1)
最佳做法是使用另一个计算属性:
computed:{
fileOptions() {
let fileOptions = [
{
event:'event',
name:'Abcd',
disabled: this.isAbcdDisabled, // based upon some condition,
display: this.isAbcdVisible // based upon some condition,
},
{
event: this.getEventName, // based upon some condition,
name:'Open Presentation',
disabled: this.getDisabled(this.getEventName), // based upon some condition,
display: this.getVisible(this.getEventName) //based upon some condition
},
]
},
isAbcdDisabled ()
{
return this.state.libraryActive === 'presentations' && !this.admin ? false : true
},
isAbcdVisible ()
{
return true;
},
getEventName ()
{
return this.canEdit ? 'edit' : 'add';
}
},
methods:
{
getDisabled (eventName)
{
switch(eventName)
{
case 'edit': return false;
case 'add': return true;
default: return false;
}
},
getVisible (eventName)
{
switch(eventName)
{
case 'edit': return true;
case 'add': return true;
default: return false;
}
},
}
答案 1 :(得分:0)
您不需要使用三元运算符,可以使其变得更加容易:
disabled: this.state.libraryActive !== 'presentations'
如果false
等于this.state.libraryActive
,则返回'presentations'
,否则返回true
。