我正在尝试在Vue.js(最近才开始学习)中切换元素的类(单击按钮的父级)。
这个想法是当disabled
为 not true时,将应用included
类。
我已经创建了一个toggleClass函数,但似乎并没有被调用。
https://codepen.io/dagford/pen/NzQrJM
HTML
<div id="app">
<div class="item" v-for="item in items" :id="item.id" :key="item.id">
<span>{{item.amt}}</span>
<button v-on:click="item.included = !item.included" v-on:click="toggleClass()">exclude me</buton>
</div>
<br>
<div id="total">total: {{ itemTotal }}</div>
</div>
VUE
var app = new Vue({
el: "#app",
data: {
items: [
{
id: 'item1',
included: 'true',
amt: 10,
className: 'disabled'
},
{
id: 'item2',
included: 'true',
amt: 20,
className: 'disabled'
},
{
id: 'item3',
included: 'true',
amt: 30,
className: 'disabled'
}
]
},
methods: {
toggleClass: function () {
if(this.included) {
console.log('test');
// code to toggle the 'disabled' class here?
}
}
},
computed: {
itemTotal() {
return this.items.reduce(function (sum, item) {
if (item.included) {
return item.amt + sum;
}
return sum;
}, 0)
}
}
});
答案 0 :(得分:0)
<div v-bind:class="{ disabled:!included }"></div>
也许尝试使用类绑定: doc
答案 1 :(得分:0)
感谢蒂莫西的建议,使它能够正常工作,几乎在那里。它只是缺少.item
部分。
应该是
<div v-bind:class="{ disabled:!item.included }"></div>