1
votes

I'm trying to bind a class like so:

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

Except that fontWeight doesn't exist yet when the component is mounted.

Here's my object:

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

So when I add the fontWeight property and it's value it doesn't set the active class.

3

3 Answers

0
votes

You could use vm.$set (as you can read here) to add the new property:

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

In this way it will be reactive and changes will be detected.

0
votes

You need to add fontWeight to your data object and give it a default value so fontWeight exists on mounted.

0
votes

Because the property fontWeight ain't declared it is not reactive.Hence you will need to declare it in the declaration of object.

In this the class is binding properly on change of value in the property on 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:''
    },
        }

  }
})

Refer the below fiddle for the solution. https://jsfiddle.net/xgh63uLo/

If u don't want to declare the property in advance you may use Vue.$set to set the new property with making it reactive Check below link https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats