Reputation: 1055
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);
}
}
})
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?
Upvotes: 3
Views: 4229
Reputation: 18187
Combine the class attributes:
:class="`star ${obj.selected ? 'gold' : ''}`"
methods:{
clickStar () {
if (this.obj.hasOwnProperty('selected') {
this.obj.selected = !this.obj.selected
} else {
this.$set(this.obj, 'selected', true);
}
}
}
Another approach would be to use a ref
:
<span ref="star" class="star" @click="clickStar">star</span>
methods:{
clickStar () {
if (this.obj.hasOwnProperty('selected') {
this.obj.selected = !this.obj.selected
} else {
this.$set(this.obj, 'selected', true);
}
if (this.obj.selected) {
this.$refs.star.$el.classList.add('gold')
} else {
this.$refs.star.$el.classList.remove('gold')
}
}
}
Upvotes: 0
Reputation: 323
you should define all of your data properties when it initialsed.
change your data object to.
data : {
object: {
selected:false
}
}
fiddle updated js fiddle
Upvotes: 1