gpt4 book ai didi

javascript - 如何根据id在vuejs 2中添加或删除类

转载 作者:行者123 更新时间:2023-11-28 17:37:22 24 4
gpt4 key购买 nike

我想使用 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>

最佳答案

以下是使用组件来实现您正在寻找的行为的示例:

// 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>

关于javascript - 如何根据id在vuejs 2中添加或删除类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48796134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com