Answer the question
In order to leave comments, you need to log in
How to make independent class switches in vue?
When clicking on one button, the class is placed on all divs (looking at the js code, this is expected). How to organize the code so that the class is switched only for the block that you click on?
<div id="app">
<div class="toggle1" :class="{_active: isActive}" @click="toogle">Toggle 1</div>
<div class="toggle2" :class="{_active: isActive}" @click="toogle">Toggle 2</div>
</div>
.toggle1, .toggle2 {
background: #555;
height: 50px;
width: 100px;
color: #fff;
text-align: center;
margin-bottom: 30px;
}
._active {
background: green !important;
}
let app = new Vue({
el: '#app',
data: {
isActive: false
},
methods: {
toogle: function() {
this.isActive = !this.isActive;
}
}
});
Answer the question
In order to leave comments, you need to log in
data: () => ({
items: [
{ active: false, text: '...' },
{ active: false, text: '...' },
...
],
}),
<div
v-for="n in items"
v-text="n.text"
:class="[ { active: n.active }, 'toggle' ]"
@click="n.active = !n.active"
></div>
but how to do it in order not to fence a bunch of data in data?
data: () => ({
itemsCount: 5,
active: [],
}),
methods: {
toggle(item) {
const i = this.active.indexOf(item);
if (i === -1) {
this.active.push(item);
} else {
this.active.splice(i, 1);
}
},
},
<div
v-for="i in itemsCount"
v-text="`Item ${i}`"
:class="[ { active: active.includes(i) }, 'toggle' ]"
@click="toggle(i)"
></div>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question