【问题标题】:vue js - conditional styling is not workingvue js - 条件样式不起作用
【发布时间】: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


    【解决方案1】:

    styleObject 应该返回一个对象,因为在 Vue 中绑定 style 属性是在对象或数组语法中。

    styleObject() {
      return this.isFavorited ? { color: 'red' } : { color: 'white' };
    }
    

    @Terry 提供的更好解决方案:

    styleObject() {
      return { color: this.isFavorited ? 'red' : 'white' };
    }
    

    【讨论】:

    • 更好:return { color: this.isFavorited ? 'red' : 'white' };
    • 我会把它添加到帖子中:)
    • @FloWy 这就是我的按钮 classes() 工作的原因吗?
    • 对,就是数组语法。
    • 您可以在docs找到更多信息
    猜你喜欢
    • 2018-04-09
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    • 2012-12-08
    • 2021-01-07
    • 2020-11-03
    相关资源
    最近更新 更多