我阅读了VueJs文档,它建议使用computed
属性来计算或切换元素类,但我无法在v-for
循环中执行此操作。我所做的是:
模板
<li v-bind:click="onClick(word)" v-bind:class="calculateClass(word)" v-for="word in words">{{ word.name }}</li>
代码
data: {
words : [{name:'ali', clicked : 1},{name:'sara', clicked : 0},{name:'marya', clicked : 1}]
},
methods: {
calculateClass : function (word) {
return {
"classA": word.clicked=== 1,
"classB" : word.clicked === 0,
'test' : true // allways return 'test' class
}
},
onClick: function (word) {
// changing the `clicked` property of related object in this.words array
for (var i in this.words) {
if (this.words[i].name === word.name) {
this.$set(this.words[i], 'clicked', 1)
break; //Stop this loop, we found it!
}
}
}
},
这是有效的,但这种方法有问题吗?我没有看到使用方法计算类的其他示例。我应该用computed
执行此操作吗?怎么样?有没有更好的办法?
答案 0 :(得分:1)
你是正确的,计算属性不能接受一个参数,因此,在这种情况下,它并不真正适合。
按照您的方式使用方法没有任何问题。