[Vuejs]-Vue.js: ":class" cause the classList is wrong

1👍

Because you are not using Vue to add class to the element. So Vue doesn’t know you have added a new class to the element.

See this example where I add a class NOT using Vue:

new Vue({
  el: '#app',
  template: `
    <div>
      <div ref="e" class="a" :class="{ b: b }"></div>
      <button @click="toggleB">Toggle B</button>
      <button @click="addC">Add C</button>
    </div>
  `,
  data(){
    return {
      b: true
    }
  },
  methods: {
    toggleB(){
      this.b = !this.b;
    },
    addC(){
      this.$refs.e.classList.add('c');
    }
  }
});
.a {
  width: 100px;
  height: 100px;
}

.b {
  border: 1px solid black;
}

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

<div id="app"></div>

Now if I use Vue to add class to it, it will work because now Vue knows:

new Vue({
  el: '#app',
  template: `
    <div>
      <div class="a" :class="{ b: b, c: c }"></div>
      <button @click="toggleB">Toggle B</button>
      <button @click="addC">Add C</button>
    </div>
  `,
  data(){
    return {
      b: true,
      c: false
    }
  },
  methods: {
    toggleB(){
      this.b = !this.b;
    },
    addC(){
      this.c = true;
    }
  }
});
.a {
  width: 100px;
  height: 100px;
}

.b {
  border: 1px solid black;
}

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

<div id="app"></div>
👤yqlim

Leave a comment