1

I am new for learning vue.Now I have some problems.My code listed below is using for change the button color when you click on it.But now it can not work.Please give me some advice.Thank you very much!

let app = new Vue({
  el: '#app',
  data: {
    isActive: [true, false, false, false],
    movies: ['A', 'B', 'C', 'D'],
  },
  methods: {
    onClick(index) {
      this.isActive[index] = !this.isActive[index];
    }
  },
});
ul li {
  list-style: none;
}

.active {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <ul>
    <li v-for="(item, index) in movies">
      <button :class="{active: isActive[index]}" @click="onClick(index)">{{ item }}</button>
    </li>
  </ul>
</div>

2
  • 2
    it is an array, use Vue.set or this.$set ;) Commented Dec 14, 2020 at 16:04
  • 2
    You are directly changing the array index value, which does not trigger reactivity and rerender of the component. Commented Dec 14, 2020 at 16:08

1 Answer 1

2

When you are working with array in Vue 2 the best way to updating array indices by $set method.

let app = new Vue({
  el: '#app',
  data: {
    isActive: [true, false, false, false],
    movies: ['A', 'B', 'C', 'D'],
  },
  methods: {
    onClick(index) {
      this.$set(this.isActive,index,!this.isActive[index])
    }
  },
});
ul li {
  list-style: none;
}

.active {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <ul>
    <li v-for="(item, index) in movies">
      <button :class="{active: isActive[index]}" @click="onClick(index)">{{ item }}</button>
    </li>
  </ul>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.