我想使用vuejs在基于id的元素中添加或删除类,但是此代码将行为应用于所有元素。如何通过id向元素添加/删除类?提前全部谢谢。
new Vue({
el:"#test",
data: {
msg: 'msg goes here',
isActive: false
},
methods: {
log: function(e) {
this.isActive = ! this.isActive
//alert(e.currentTarget.id);
}
}
});

.active {
background: red
}

<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script>
<div id="test">
<div id="1" v-on:click="log($event)" v-bind:class="{ active: isActive }">
{{ msg }}
</div>
<div id="2" v-on:click="log($event)" v-bind:class="{ active: isActive }">
{{ msg }}
</div>
</div>
&#13;
答案 0 :(得分:3)
以下是使用组件来实现您正在寻找的行为的示例:
// register
const clickable = Vue.component('clickable', {
props: ['msg'],
data: function() {
return {
isActive: false
}
},
template: '<div :class="{ active: isActive }" @click="isActive = !isActive">{{ msg }}</div>'
})
new Vue({
el: "#test",
components: {
clickable
},
data: function() {
return {
msg: 'msg goes here',
isActive: false
}
}
});
.active {
background: red
}
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script>
<div id="test">
<clickable :msg='msg'></clickable>
<clickable :msg='msg'></clickable>
</div>
答案 1 :(得分:0)