【发布时间】:2021-06-06 06:12:16
【问题描述】:
我有一个带有提交按钮的心形符号,点击它后,颜色应该会改变。
我的代码:
<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++;
}
}
}
所以我将图标绑定到 styleObject 并单击按钮后,除非我刷新页面,否则颜色不会改变。但是类按钮按预期工作。
我也尝试使用内联样式绑定这样编写它:
<span class="fas fa-heart fa-sm" v-bind:style="[this.isFavorited ? {'color' : 'red'} : {'color' : 'white'}]"></span>
也是这样:
styleObject(){
return { color: this.isFavorited ? 'red' : 'white' };
}
我尝试使用 vue 开发工具对其进行检查,它确实显示颜色在单击时发生了变化,但它没有反映在我的屏幕上。
我该如何解决这个问题?
【问题讨论】:
标签: javascript vue.js