I want to add or remove class to an element based on id using vuejs, but this code applies the behaviour to all elements. How can I add/remove a class to the element by id? Thanks all in advance.
JavaScript
x
13
13
1
new Vue({
2
el:"#test",
3
data: {
4
msg: 'msg goes here',
5
isActive: false
6
},
7
methods: {
8
log: function(e) {
9
this.isActive = ! this.isActive
10
//alert(e.currentTarget.id);
11
}
12
}
13
});
JavaScript
1
3
1
.active {
2
background: red
3
}
JavaScript
1
15
15
1
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script>
2
3
<div id="test">
4
5
<div id="1" v-on:click="log($event)" v-bind:class="{ active: isActive }">
6
{{ msg }}
7
</div>
8
9
10
<div id="2" v-on:click="log($event)" v-bind:class="{ active: isActive }">
11
{{ msg }}
12
</div>
13
14
15
</div>
Advertisement
Answer
Here is an example of using components to achieve the behavior you are looking for:
JavaScript
1
23
23
1
// register
2
const clickable = Vue.component('clickable', {
3
props: ['msg'],
4
data: function() {
5
return {
6
isActive: false
7
}
8
},
9
template: '<div :class="{ active: isActive }" @click="isActive = !isActive">{{ msg }}</div>'
10
})
11
12
new Vue({
13
el: "#test",
14
components: {
15
clickable
16
},
17
data: function() {
18
return {
19
msg: 'msg goes here',
20
isActive: false
21
}
22
}
23
});
JavaScript
1
3
1
.active {
2
background: red
3
}
JavaScript
1
9
1
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script>
2
3
<div id="test">
4
5
<clickable :msg='msg'></clickable>
6
7
<clickable :msg='msg'></clickable>
8
9
</div>