When utilizing Vue, it seems that developers often use v-bind:class
to add dynamic classes to elements. However, in the example below, this method appears to not function as expected.
//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);
}
}
})
Upon clicking the span
element, the value of obj.selected
changes due to the clickStar
function. Unfortunately, the v-bind:class
does not update despite using $set
to alter the values in obj
.
To understand why the DOM is not updating, you may visit this link: Reason that Dom is not updated
Have I made an error? How can I rectify this issue?