Vue doesn't rerender binded class when data changes

Viewed 887

Vue doesn't rerender binded class when data changes

I declared data 'isLoading' with default value and binded in html tag and also declared method that changes the data.

Please see the code below!

style

  .is-red{
    background: red;
  }
  .is-blue{
    background: blue;
  }

script

export default {
    created() {
      this.isLoading = true;
    },
    mounted() {

    },
    data() {
      return {
        isloading: true
      };
    },
    methods: {
      changeColor() {
        this.isLoading = !this.isLoading;
        console.log(this.isLoading);
      }
    }
  }

html

<h1 v-bind:class="{'is-blue': isLoading, 'is-red': !isLoading }">hello</h1>
<button @click="changeColor">toggle</button>

I can see the data switching between 'true' and 'false' in the console log. However nothing changes in DOM.

what is the problem?

2 Answers

You declared your variable with name isloading. And you declare isLoading in created.Vue won't Observe changes on dynamic variables.

To update dynamic variables inside a component use Vue.set() or this.$set().

Your script:

export default {
    mounted() {

    },
    data() {
      return {
        isLoading: true
      };
    },
    methods: {
      changeColor() {
          this.isLoading = !this.isLoading;
      }
   }
}

try to use computed like below

script

export default {
    data() {
        return {
            isloading: true
        };
    },
    computed:{
        classes(){
            return this.isloading ? 'is-blue' : 'is-red';
        }
    },
    methods: {
        changeColor() {
            this.isLoading = !this.isLoading;
            console.log(this.isLoading);
        }
    }
}

html

<h1 :class="classes">hello</h1>
<button @click="changeColor">toggle</button>
Related