[Vuejs]-Vue add property to data root level and make it reactive

3👍

The docs clearly say you cannot add top level keys.

Vue does not allow dynamically adding new root-level reactive properties to an already created instance.

You must add a key to the root level object so you can update it later.

You can either:

  • create a key with a default value that you’ll update. This means that you know the key before hand
  • create an empty object with a generic key (for instance dynamicProps) and use Vue.set to add dynamic keys at runtime to it.

1👍

The question is simple: How to create a root level property and make it reactive?

The properties in data are only reactive if they existed when the instance was created. That means if you add a new property, like:

myData.b = 12;

Then changes to b will not trigger any view updates. If you know you’ll need a property later, but it starts out empty or non-existent, you’ll need to set some initial value. For example:

let myData = { a: 1, b: 0 }
// or,
let myData = { a: 1, b: null }

Now you can see changes to b are showing in the UI also:

let myData = { a: 1, b: 0 }
const app = new Vue({
  el: "#myApp",
  data: myData
})

myData.b = 12;
console.log(app.$data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="myApp">
  <pre>{{ b }} </pre>
</div>

0👍

I can’t find in documentation if you can add property to the root level and make it also reactive, but there is alternative solution.

let myData = {
    obj: {
     a: 1
    }
}

const app = new Vue({
    data: myData,
    watch: {
      obj: {
        handler(val) {
          console.log('watching !', val)
        },
        deep: true
      }
    }
});

Vue.set(app.obj, 'b', 12)

console.log(app.$data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

Leave a comment