Javascript vue js-条件样式设置不起作用
我有一个心形符号和一个提交按钮,点击它,颜色应该会改变 我的代码:Javascript vue js-条件样式设置不起作用,javascript,vue.js,Javascript,Vue.js,我有一个心形符号和一个提交按钮,点击它,颜色应该会改变 我的代码: <template> <button v-bind:class="classes" type="submit" @click="toggle"> <span v-text="this.count"></span> <i clas
<template>
<button v-bind:class="classes" type="submit" @click="toggle">
<span v-text="this.count"></span>
<i class="fas fa-heart fa-sm" v-bind:style="styleObject"></i>
</button>
</template>
<script>
export default {
props: ['reply'],
data(){
return {
isFavorited: this.reply.isFavorited,
count: this.reply.favorites_count
}
},
computed: {
classes(){
return ['btn',this.isFavorited ? 'btn-primary':'btn-secondary'];
},
styleObject(){
return this.isFavorited ? 'color:red':'color:white';
}
},
.......
methods: {
toggle(){
// check if reply is favorited
if(this.isFavorited){
axios.delete('/replies/'+this.reply.id+'/favorites');
this.isFavorited = false;
this.count--;
}else{
axios.post('/replies/'+this.reply.id+'/favorites');
this.isFavorited = true;
this.count++;
}
}
}
我尝试使用vue dev工具检查它,它确实显示单击后颜色发生了变化,但它没有反映在我的屏幕上
如何解决此问题?由于在Vue中绑定
style
属性采用对象或数组语法,因此样式对象应返回一个对象
styleObject(){
返回this.isFavorited?{color:'red'}:{color:'white'};
}
@Terry提供更好的解决方案:
styleObject() {
return { color: this.isFavorited ? 'red' : 'white' };
}
更好的是:return{color:this.isFavorited?'red':'white'}代码>我将把它添加到帖子:)@FloWy这就是我的按钮类()工作的原因吗?是的,这就是数组语法。你可以在
styleObject(){
return { color: this.isFavorited ? 'red' : 'white' };
}
styleObject() {
return { color: this.isFavorited ? 'red' : 'white' };
}