2

I have a heart symbol attached with a submit button that upon clicking it, the color should changed.

My code:

 <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++;
            }
        }
    }  

So I bind the icon to styleObject and upon clicking the button, the color is not changing unless I refresh the page.The class button however is working as expected.

I also tried writing it like this using inline style binding:

 <span class="fas fa-heart fa-sm" v-bind:style="[this.isFavorited ? {'color' : 'red'} : {'color' : 'white'}]"></span>

and also this way:

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

I tried inspect it using vue dev tool and it does show the color has changed upon clicking but it's not reflecting on my screen.

How do I fix this?

1 Answer 1

1

The styleObject should return an object, because in Vue the binding style attribute is in an object or array syntax.

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

Better solution by @Terry:

styleObject() {
  return { color: this.isFavorited ? 'red' : 'white' };
}
Sign up to request clarification or add additional context in comments.

17 Comments

Even better: return { color: this.isFavorited ? 'red' : 'white' };
I will add that to the post :)
@FloWy Is that why my button classes() is working?
Yes, that is the array syntax.
You can find more information in the docs
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.