Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue v-bind:class not working immediately when changing the binded object's value

In the Vue, to add the dynamical class to the element, I think that the developers use the v-bind:class.
But in the below example, the v-bind:class doesn't work properly.

//Html
<div id="mainapp">
  <span class="star" v-bind:class="{gold:obj.selected}" v-on:click="clickStar()">star</span>
</div>

//Script
var app = new Vue({
  el:"#mainapp",
  data:{
    obj:{}  
  },
  methods:{
    clickStar:function(){
      if(this.obj.selected == undefined) this.obj.selected =false;
      //this.obj.selected=!this.obj.selected;
      this.$set(this.obj, 'selected', !this.obj.selected);
      console.log(this.obj);
    }
  }
})

JsFiddle Example

When clicking the element , span tag, the obj.selected value is changed by the clickStar function.
But v-bind:class doesn't work though $set is used when changing the obj.
Reason that Dom is not updated
What am I wrong? How could I solve this issue?

like image 787
Andrew Li Avatar asked Aug 16 '26 00:08

Andrew Li


1 Answers

you should define all of your data properties when it initialsed.

change your data object to.

data : { object: { selected:false
} }

fiddle updated js fiddle

like image 152
hema sundar Ginni Avatar answered Aug 18 '26 15:08

hema sundar Ginni