Vue.js - experiencing issues with conditional styling not functioning as expected

Can someone help me with an issue I'm having? I've created a button with a heart symbol that is supposed to change color when clicked, but it's not working as expected.

This is my current 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++;
            }
        }
    }  

When using the inline style binding or the styleObject, the color doesn't change unless I refresh the page. The button class works fine though.

I have also tried other methods like:

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

and this way:

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

The Vue dev tool shows that the color has changed upon clicking, but it's not reflecting on the screen. Any suggestions on how to fix this?

Answer №1

When working with Vue, the styleObject function should always return an object. This is because the style attribute in Vue requires either an object or array syntax for proper binding.

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

A more concise solution was provided by @Terry:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

looping through the elements in a collection using a for-in loop

Issue with IE 11 Console Chrome Console Behavior When changing the word 'item' to 'anotherItem' in the loop like so: var obj = { id1: 'item 1', id2: 'item 2', id3: 'item 3' }; for (anothe ...

Setting up Eslint Airbnb with VScode in a Vue project for optimal code formatting and style enforcement

This is my Vue.js code without proper linting. After running npm run lint --fix The code now looks like this However, when I make changes and press Control + C, it reverts back to the old formatting with the same linting errors. I suspect that my co ...

Is there a way to remove a value from the search bar while updating the table at the same time?

Although I can successfully search the table based on the values in my search bar, I am having trouble with updating the state when deleting a value. To see my code in action, check out my sandbox here. ...

The changing of colors does not function properly when clicked in JavaScript

I am having an issue with a drop-down list that offers two options: blue and green. When I select blue and click on the text input field, its background color alternates between blue and black (the default text field color). The same applies when I choose ...

Attempt the axios request again if the response is null or missing

await axios .post( executeBatch, { headers: { "Content-Type": "application/json", "x-access-token": localStorage.getItem("token"), }, } ) .then( ...

Is Grouping Together Installed Private Modules Possible?

Exploring a modular JavaScript approach in my upcoming project is a new concept for me. I would prefer explanations to be simple due to my limited experience. I have uploaded my private package on npm: @name/package-name The private package contains mul ...

Can preloading data from a website impact the accuracy of my google analytics data?

I am interested in creating a simple script that utilizes AJAX to load the content from each page listed in my main navbar into a hidden div on the current page. My goal is to preload important content and cache it on the user's computer to ensure fa ...

The tsconfig.json file is located separate from the project directory

Working on my project called "portal" has been quite an interesting journey. As I delved deeper into development, I realized the need for multiple projects within the repository. This led me to restructure my project setup like this: A question popped up ...

Guide to implementing onhashchange with dynamic elements

Hey there! I've encountered a problem with two select boxes on my webpage, each in different anchors (one on the page, the other in an iframe). What I'm trying to achieve is for the code to recognize which anchor it's in and then pass the se ...

Change the date string to year, month, and day

When using Ajax's getResponseHeader("Last-Modified"), it returns a date string with the format displayed below: Thu Oct 13 2016 13:05:17 GMT+0200 (Paris, Madrid, sommartid) I am wondering if it is achievable in javascript to extract the year, month, ...

Rxjs: Making recursive HTTP requests with a condition-based approach

To obtain a list of records, I use the following command to retrieve a set number of records. For example, in the code snippet below, it fetches 100 records by passing the pageIndex value and increasing it with each request to get the next 100 records: thi ...

HTML: Efficiently updating multiple cell contents in a large table using jQuery or JavaScript

Hello, I am currently working on developing an HTML page that consists of a large data table. My goal is to have the data in the table update dynamically as the user interacts with various controls on the page, without having to reload the entire page. ...

Position the typography component to the right side

Is there a way to align two typography components on the same line, with one aligned to the left and the other to the right? I'm currently using this code but the components are aligned next to each other on the left side. const customStyles = makeSt ...

Determining the successful completion of an ajax request using jQuery editable plugin

I recently started using Jeditable to enable inline editing on my website. $(".video_content_right .project_description").editable(BASE_URL+"/update/description", { indicator: "<img src='" + BASE_URL + "/resources/assets/front/images/indicator ...

How can I simulate the response of a VueX action using Vue-test-utils?

I am currently developing a test for a Vue component that interacts with a module store to execute an action and utilize the result from it. Since the action involves making requests to our API, I prefer not to run the test using the actual action. Instea ...

Utilizing .isDisplayed() in conjunction with .each() in ProtractorJS for Angular: A guide

Currently, I am working on setting up a test within my Angular application. The goal of this test is to click on an element and check if a specific object is displayed. While I believe the code provided below should work, I am aware that the isDisplayed( ...

Save user input data into an Excel file using PHPExcel

Could someone assist me with storing values from my form inputs to Excel using PHPExcel? I have successfully stored data from my table to Excel, but now I want to store the values from my inputs. Can anyone help me, please? Example of the form inputs: ent ...

Fix a typing issue with TypeScript on a coding assistant

I'm struggling with typing a helper function. I need to replace null values in an object with empty strings while preserving the key-value relationships in typescript // from { name: string | undefined url: string | null | undefined icon: ...

The production build encountered an error after upgrading Angular due to a problem with document.documentElement.setAttribute not being recognized

Recently, I updated my application to Angular 16 and the upgrade was successful. The application is running smoothly without any issues. However, when I attempted to run the command for a production build, ng build --configuration=production I encountere ...

It appears that Next.js's useDebouncedCallback function is not effectively delaying the request

I am currently learning Next.js and trying to work through the tutorial. I have hit a roadblock on this particular page: https://nextjs.org/learn/dashboard-app/adding-search-and-pagination Despite conducting an extensive web search, I couldn't find a ...