2017-07-30 28 views
1

我读过VueJs文档,它建议使用computed属性来计算或切换一个元素类,但我无法在v-for循环内执行该操作。我做了什么,而不是是这样的:在v-for内切换VueJs2的元素类,这是否正确?

模板

<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?怎么样?有没有更好的办法?

回答

1

你是正确的,一个计算属性不能接受一个参数,因此,在这种情况下,不适合。

按照自己的方式使用方法没有任何问题。