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

Creating files for two HTML pages with Vue: A step-by-step guide

Currently, I am working on creating two HTML files as part of my project structure. This is how it looks: |- node_modules |- public | |- blog | | |- some-page.html | |- index.html |- src (contains all the Vue components) |- Blog.Vue |- Index.Vue ...

What is the best way to link buttons to specific drop down sections?

How can I create multiple drop down divs with different content for each button click? JSFiddle: http://jsfiddle.net/maddiwu/xe6xtfqh/ .slide { overflow-y: hidden; max-width: 100%; overflow-x: hidden; max-height: 100vw; /* approximate ...

press a cURL PHP ajax button to trigger an action

Hello everyone, I could really use some help here. I've been looking at similar questions but none of the answers seem to apply to my situation. I extracted a page using curl, however, there's a button on that page that I am unable to interact w ...

Managing touchEvents in Vue: A comprehensive guide

Is it possible to manage touch events in Vue3 without using an external library? I am trying to make an element draggable (drag and drop to another location) with touch input. The elements are generated using v-for. I was able to implement mouse control w ...

When a user clicks a button, modify a section of the URL and navigate to

I've been searching everywhere for a solution to this issue, but I just can't seem to find it. I'm hoping someone here can help me out. In a bilingual store, I need a way to redirect users to the same product on a different domain when they ...

Tips for implementing multiple middlewares in Next.js using the middleware.ts script

In the development of my Next.js project, I am exploring the implementation of multiple middleware without depending on external packages. Although I have seen examples of using a single middleware in Next.js with the next-connect package, I aim to achieve ...

Passing down slots to child components in Vue allows for flexible and dynamic content

I am looking to create a reusable Data Table component using Vuetify. Some columns may require the use of v-slot to modify the data displayed within that specific column. For example, I have user roles stored as integers and want them to be shown as either ...

Executing external Javascript within an HTML document

Just diving into this realm, so please have patience with me. I've got an external js file linked in my HTML. The JS code is solid and functions properly in Fiddle - https://jsfiddle.net/0hu4fs4y/ <script src="js/noti.js"></script> <sc ...

Discovering the automatically generated routes in Nuxtjs

Can I access the route list created by Nuxt.js based on pages folder items? The issue is that I am unsure of the exact route name generated for each component. $router.push({name: 'no-idea-what-the-route-name-is', query: { id: data.id } }) This ...

Searching for a way to detect when a user clicks the back button on their Android or iPhone device using JavaScript or

In the process of building a Single Page Application (HTML5) utilizing the following plugins: - Sammy.js - Knockout.js - Require.js - Jquery.js This app is designed for Android, iPhone, and Windows mobile devices. Many scenarios revolve around cli ...

Switch between different table rows

I have here a table that is used for displaying menu and submenu items. It's a mix of PHP (to fetch the menu items and their respective submenus) and HTML. What I am trying to figure out is how to toggle the visibility of only the submenu items under ...

Dynamic addition of CSS classes to HTML elements using PHP

I'm working on developing an application that includes multiple courses. Each course is completed over a certain number of days, such as 14 days or 20 days. To visually track progress, I've implemented a step progress bar that looks like this:htt ...

Ways to incorporate a custom JavaScript function that is activated by an external server system?

I'm currently exploring a JavaScript widget that needs to operate within specific constraints: The widget initiates a request to a third-party server using a callback URL The third-party server pings the callback URL after a set period, triggering a ...

Can a Unicode character be overwritten using a specific method?

Is there a way to display a number on top of the unicode character '♤' without using images? I have over 200 ♤ symbols each with a unique number, and using images would take up too much space. The characters will need to be different sizes, a ...

I am having trouble getting the filter functionality to work in my specific situation with AngularJS

I inserted this code snippet within my <li> tag (line 5) but it displayed as blank. | filter: {tabs.tabId: currentTab} To view a demo of my app, visit http://jsfiddle.net/8Ub6n/8/ This is the HTML code: <ul ng-repeat="friend in user"> ...

A guide on transferring radio button values to another program and saving them into a database with the help of PHP and jQuery

I have encountered an issue with storing radio button values in a database. Specifically, I want to assign the value of 1 for "Yes" and 0 for "No". To accomplish this, I am utilizing two scripts - a.php and b.php. The former obtains the radio button values ...

Validation check: Ensure that the value does not match any other field

Looking for a method to compare two fields and only validate them if they are not equal. This is the approach I've tried, but it's not working: yup .number() .required() .notOneOf( [FormField.houseHoldMembers as any], &ap ...

Having trouble with the functionality of Bootstrap's nav-tabs 'show' feature?

I'm having some issues with adding a search box to my glossary. The glossary is created using nested unordered lists (ul) within another ul that has classes of "nav-tabs" and "bootstrap". In the JavaScript code, I am using the following snippet: $j(& ...

Is it possible to spread an empty array in JavaScript?

Whenever I run the code below, I encounter the error message Uncaught SyntaxError: expected expression, got '...': [1,2,3, (true ? 4 : ...[])] I'm wondering if spreading an empty array in that manner is allowed? ...

What is the method to retrieve the local filepath from a file input using Javascript in Internet Explorer 9?

I'm experiencing some issues with the image-preview function on IE9, similar to the example photo shown. This method is not functioning properly and throwing an error in IE9, while it works perfectly fine in IE6-8. I am looking for a way to retrieve ...