The Vue v-bind:class feature does not always update immediately when the value of the binded object is changed

When utilizing Vue, it seems that developers often use v-bind:class to add dynamic classes to elements. However, in the example below, this method appears to not function as expected.

//Html
<div id="mainapp">
  <span class="star" v-bind:class="{gold:obj.selected}" v-on:click="clickStar()">star</span>
</div>

//Script
var app = new Vue({
  el:"#mainapp",
  data:{
    obj:{}  
  },
  methods:{
    clickStar:function(){
      if(this.obj.selected == undefined) this.obj.selected =false;
      //this.obj.selected=!this.obj.selected;
      this.$set(this.obj, 'selected', !this.obj.selected);
      console.log(this.obj);
    }
  }
})

JsFiddle Example

Upon clicking the span element, the value of obj.selected changes due to the clickStar function. Unfortunately, the v-bind:class does not update despite using $set to alter the values in obj.

To understand why the DOM is not updating, you may visit this link: Reason that Dom is not updated
Have I made an error? How can I rectify this issue?

Answer №1

It is important to establish all data properties during initialization.

Modify your data object as follows:

data : {
    object: {
       selected:false<br>
    }
 }

Check out the updated JSFiddle link

Answer №2

Blend the different classes together:

:class="`star ${obj.selected ? 'gold' : ''}`"

methods:{
  clickStar () {
    if (this.obj.hasOwnProperty('selected') {
      this.obj.selected = !this.obj.selected
    } else {
      this.$set(this.obj, 'selected', true);
    }
  }
}

Including reactive properties

Alternatively, you can opt for utilizing a ref:

<span ref="star" class="star" @click="clickStar">star</span>

methods:{
  clickStar () {
    if (this.obj.hasOwnProperty('selected') {
      this.obj.selected = !this.obj.selected
    } else {
      this.$set(this.obj, 'selected', true);
    }

    if (this.obj.selected) {
      this.$refs.star.$el.classList.add('gold')
    } else {
      this.$refs.star.$el.classList.remove('gold')
    }
  }
}

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

Button cannot be activated upon selecting a row

The goal is to activate a button when a row is selected. However, the button remains disabled even after selecting a row. Below is a snippet of the code as well as a screenshot showing the issue [error_1]: onInit: function () { var oViewMode ...

Multiple invocations of Vue.js function

When running the code and checking the browser console, you may notice that the function "formatName()" is being called multiple times. But why does this happen if the race data isn't being updated? Well, changing the function "amIStarted()" to "retur ...

Using CSS to automatically adjust the width of a child div based on its content, rather than stretching it to fill the entire

I'm currently facing an issue with my CSS. Apologies for the vague title, but I'll do my best to explain it here. My problem lies within a parent wrapper div that is centered on the page. Within this wrapper, there is another child div containing ...

"Exploring the world of Mean.js with Node.js background functionalities

Struggling with my mean.js app as I try to figure out how to implement background processes. I want these processes to run continuously, interacting with the mongodb database and handling tasks like cleanup, email notifications, and tweets. I need access ...

Utilize jQuery to transform array values into date objects

I am receiving an array from a .net controller. The values I am getting for dates are: /Date(1445256000000)/ and /Date(1445256900000)/ Instead of this, I need to convert these into proper date values. Now that I have an array of objects, I want to upda ...

Angular view fails to update after form submission when using ngDialog to change the scope

After starting my Angular journey, I decided to challenge myself by creating a comprehensive todo app for educational purposes. I seem to be missing something pretty basic, although I can't quite put my finger on it. It seems like there might be an is ...

Utilizing PHP to dynamically load HTML forms and leveraging JQuery for form submissions

I am currently facing a dilemma that I am unsure how to approach. It seems that JQuery requires unique ID's in order to be called in the document ready function. I use PHP to read my MySQL table and print out HTML forms, each with a button that adds a ...

Importing Global Sass Styles in Nuxt 3 for Static Assets

I'm currently attempting to import a global Sass stylesheet from the /assets directory in order to utilize variables and mixins defined there throughout the components. My current configuration in nuxt.config.ts is as follows: import { defineNuxtConfi ...

Error message: npm command not recognized while running commands within an Electron application

While developing an electron app, I utilize shell commands with child_process.exec. One of the commands I use is npm run start, which functions perfectly in a development environment. However, upon building the application for production, all npm commands ...

JavaScript confirmation for PHP delete button

Is there a way to implement a JavaScript alert that prompts the user to confirm their action when they click the delete button? I attempted to integrate a class into an alert box: <?php //$con = mysqli_connect("localhost", "root", "root", "db"); $sql ...

What is the importance of using ChangeDetectorRef.detectChanges() in Angular when integrating with Stripe?

Currently learning about integrating stripe elements with Angular and I'm intrigued by the use of the onChange method that calls detectChanges() at the end. The onChange function acts as an event listener for the stripe card, checking for errors upon ...

What is the best way to sort through an array depending on a specific sequence of elements provided

I am trying to create a custom pipe in Angular 5 that filters an array of events based on a given sequence. For instance, if my data is: ["submit", "click", "go_back", "click",...] I want to filter this data based on up to three inputs. If input ...

Using Vue.js to pass an image URL as a prop for CSS animation by converting it to a CSS variable

Need help with a component that features a hover animation displaying 4 rotating images: animation: changeImg-1 2.5s linear infinite; @keyframes changeImg-1 { 0%, 100% { background-image: url('images/wel1.png'); } 25% { background-image: ur ...

Integrate JQuery-Ui into an Angular 7 application using an external .js file

I'm currently working on an Angular 7 project and facing some challenges while trying to integrate the JQuery-Ui plugin. I have successfully installed both JQuery and the plugin, and added them to the scripts array in my angular.json file. Even though ...

Introducing Vuetify 3's v-file-input with interactive clickable chips!

I noticed an unexpected issue with the v-file-input component in Vuetify3. In Vuetify 2, it was possible to use the selection slot to customize the display of selected files. This functionality still works in both versions, as mentioned in the documentatio ...

Is there a method to dynamically incorporate a new editable textfield row in a react table?

Is there a way to dynamically add an editable row of text fields to a table in React? Currently, when I click on the "Add" button, a new row is added to the table but it's not editable by default. The logic for adding a new row is implemented inside t ...

Determine the success of an SQL query in Node.js

I've created a basic API using nodejs to connect my Flutter app with a SQL Server database, but I have a question. How can I verify if the query was successful in order to return different results? I'm attempting an update after a successful in ...

Why is it difficult to display data fetched through getJSON?

The test-json.php script retrieves data from the database and converts it into JSON format. <?php $conn = new mysqli("localhost", "root", "xxxx", "guestbook"); $result=$conn->query("select * From lyb limit 2"); echo '['; $i=0; while($row ...

Marked checkboxes and Node.js

I'm having trouble grasping the concept of using HTML checkboxes with Node.js and Express. I have a basic form in EJS and before diving deeper into the backend logic, I want to ensure that the correct values are being retrieved. Despite my efforts to ...

Executing JavaScript code using an HTML form submission

Greetings, I have implemented an HTML form on my website for user login using AJAX (jQuery), but I am encountering some issues. Below is the JavaScript code: function validateLoginDetails() { $('[name=loginUser]').click(function() { ...