组合类属性:
: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);
}
}
}
Adding reactive properties
另一种方法是使用
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')
}
}
}