Using VueJS for reactive binding效果

I am attempting to assign a class using the following syntax:

:class="{active: favs.medium_title.fontWeight === 'bold'}"

However, the fontWeight attribute is not yet defined when the component loads.

This is an excerpt from my object:

favs: {
    ...
    medium_title: {},
    ...
}

When I later add the fontWeight property and give it a value, the active class is not applied as expected.

Answer №1

If you want the new property to be reactive and detect changes, consider using vm.$set. You can find more information about this in the official documentation.

this.$set( this.favs.medium_title , 'fontWeight' , 'bold' )

By doing this, any changes made will be properly detected by Vue.js.

Answer №2

In order to ensure that the fontWeight property is present when the component is mounted, be sure to include it in your data object with a default value.

Answer №3

Without declaring the property fontWeight, it will not be reactive. To make it reactive, you need to declare it in the object declaration.

The class binds properly when the value in the property changes upon button click.

<div id="app">
  <p :class="{active: favs.medium_title.fontWeight === 'bold'}">{{ message }}</p>
  <button @click="favs.medium_title.fontWeight = 'bold'">
  Click here
  </button>
</div>

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    favs: {
    medium_title: {
        fontWeight:''
    },
        }

  }
})

For the solution, please refer to the fiddle provided below. https://jsfiddle.net/xgh63uLo/

If you prefer not to declare the property beforehand, you can use Vue.$set to create a new reactive property. Check out the link below for more information: https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

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

Is it possible to share data from one controller in a JS file to another JS file? (using AngularJS)

I need to create a table in JavaScript. In one of my JS files, I have a controller with JSON data containing properties like width, height, color, etc. In another JS file, I am building the actual table structure. Here is an example of my AngularJS file: ...

JavaScript code returning the correct result, however, it is unable to capture all characters in the returned string

Currently, I am utilizing $.post to retrieve results from a database. The syntax I am using is as follows: $.post('addbundle_summary', {id:id}, function(resultsummary) { alert(resultsummary[0]); }) In CodeIgniter, within my model, I am retu ...

What are some methods to boost productivity during web scraping?

Currently, I have a node script dedicated to scraping information from various websites. As I aim to optimize the efficiency of this script, I am faced with the challenge that Node.js operates on a single-threaded runtime by default. However, behind the sc ...

Performing mathematical computations through a mixin without relying on inline javascript code

Looking to enhance my web app with a mixin that shows a list of entries, each with a time stamp indicating how long ago it was posted. mixin listTitles(titles) each title in titles article.leaf article a.headline(href=title.URL)= title.t ...

Unable to access a hyperlink, the URL simply disregards any parameters

When I click an a tag in React, it doesn't take me to the specified href. Instead, it removes all parameters in the URL after the "?". For example, if I'm on http://localhost:6006/iframe.html?selectedKind=Survey&selectedStory=...etc, clicking ...

Vue.js is not properly synchronizing props in a child component when the parent component is updating the property

When it comes to communication between components, my structure looks something like this: <div id=chat-box> <div class="wrapper"> <div> <chat-header></chat-header> <message-container :chat="chat"></message ...

What are the correct steps for integrating C3JS into WebPack efficiently?

Currently, I am attempting to incorporate C3JS into my VUEJS/WebPack project (based on the boilerplate found here). D3JS is successfully loaded by npm installing it and including it as a webpack plugin. However, the same approach does not seem to work for ...

Eliminate web address parameter using regular expressions

Looking to remove a specific URL parameter from a given URL. For instance, if the URL is: http://example.com?foo=bar&baz=boo And I want to eliminate foo=bar to get: http://example.com?baz=boo Or removing baz=boo would leave me with: http://exampl ...

Is the state mutated when using the .map() function to update it?

I am new to working with React and I am still struggling to understand state mutation. After reading multiple posts on this topic, I am finding it difficult to grasp the concept of state mutation. So, I have decided to seek clarification on this matter. ...

The Angular performance may be impacted by the constant recalculation of ngStyle when clicking on various input fields

I am facing a frustrating performance issue. Within my component, I have implemented ngStyle and I would rather not rewrite it. However, every time I interact with random input fields on the same page (even from another component), the ngStyle recalculate ...

Placing a div with position:absolute inside another div with position:absolute and turning them into position:fixed

HTML <div class="box1"></div> <div class="box2"> <div class="box3"></div> </div> CSS Properties of box1, box2 and box3 are: box1 { position: absolute; z-index: 100; background-color: rgba(39, 39, 39, 0.3) ...

In JavaScript, the price can be calculated and displayed instantly when a number is entered into a form using the input type 'number'

Is there a way for me to automatically calculate the price and display it as soon as I enter a number into my form? Currently, the price is only displayed after I press submit. <script type="text/javascript"> function calculatePrice() { ...

Submitting Files to the API using Vue.js

I have the following code in Vue.js and I am trying to upload a file, but my issue is that I want to save the filename of the uploaded file to the JSON API using a POST method. Is there a way to achieve this? Thank you in advance. <div class="input-f ...

The function is failing to return a false value

I have encountered a problem with my code - it works fine in Chrome but not in IE or Firefox. I've tried using return false; and event.preventDefault() but they don't seem to be effective in Firefox. The issue arises when the button grabs informa ...

Adjust the path of an element as it decreases in size

Sorry for the weird title, but that's likely why I can't find the solution on my own. I'm experimenting with CSS animations and I want the form element to decrease in height from 100px -> 0, but I want it to collapse from the top to the ...

An unexpected error occurred in the Angular unit and integration tests, throwing off the script

I seem to be facing a recurring issue while running unit/integration tests for my Angular project using Karma. The tests have a 50:50 success/failure rate, working fine on my machine but failing consistently on our build server, making the process quite un ...

Ways to identify and differentiate user clicks on various buttons

I have generated 3 different plan options from an array of objects retrieved from the backend. Depending on whether the plan is cheaper, the user's subscription, the corresponding button will display "downgrade", more expensive, the button will show ...

Dynamic TypeScript class constructor argument typing determined by user input

I am working on creating a dynamic class that can adapt its argument properties based on a certain value. To illustrate this concept, let's consider a simple example: Imagine I have a class called Customizer, and depending on the value of the mode pr ...

Combine two objects and discard any duplicate keys

I have two objects named original and custom. My goal is to merge the content from custom into original, but only update the keys in original that are also present in the custom object. Here is an example scenario: var original = { coupon: { ...

Sending an array of objects in JavaScript to a controller

I have a dynamic form that I'm trying to submit to my Controller. Instead of sending just a string or an array with data, I need to pass an array of objects using ajax request after building the Javascript Array. The challenge is that when I send only ...