当我点击按钮时,我想动态更改按钮的颜色。因此,我添加了一个自定义类" active"只应在属性isActive设置为true时分配。单击我想调用一个方法将属性更改为true,然后更新dom以添加自定义类。任何帮助表示赞赏;)
<div v-for="(funktion, index) in funktions">
<button class="btn btn-default wordcloud"
:class="{ 'custom-active': funktion.isActive }"
@click="activate(index)">{{funktion.name}}</button>
</div>
该方法正确更新数据,但dom不会更新
export default {
data() {
return {
funktions: [
{
name: "finanzen",
isActive: false
},
{
name: "management",
isActive: false
},
{
name: "testfield",
isActive: false
},
],
};
},
methods: {
activate(index){
this.funktions[index].isActive = true;
},
};
答案 0 :(得分:1)
您没有将索引传递给activate
回调。将其更改为:
@click="activate(index)">{{funktion.name}}</button>
如果你要在你的控制台中查看,你会有一个例外情况,因为你试图访问一个带有非数字的数组的项目。
new Vue({
el: '#app',
data() {
return {
funktions: [
{
name: "finanzen",
isActive: false
},
{
name: "management",
isActive: false
},
{
name: "testfield",
isActive: false
},
],
};
},
methods: {
activate(index){
this.funktions[index].isActive = true;
},
},
})
&#13;
.custom-active {
background-color: red;
}
&#13;
<script src="https://unpkg.com/vue"></script>
<div id="app">
<div v-for="(funktion, index) in funktions">
<button class="btn btn-default wordcloud"
:class="{ 'custom-active': funktion.isActive }"
@click="activate(index)">{{funktion.name}}</button>
</div>
</div>
&#13;