H
H
Heretic Man2019-03-17 17:33:26
Vue.js
Heretic Man, 2019-03-17 17:33:26

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

1 answer(s)
0
0xD34F, 2019-03-17
@heretic_man

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>

UPD. Taken from the comments:
but how to do it in order not to fence a bunch of data in data?

Like, is it better to fence an even bigger bunch of html code? No, that's not how things are done. At least when using vue, the data is primary here.
Although, it is possible without data - if you generate the markup automatically, without copy-paste:
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 question

Ask a Question

731 491 924 answers to any question