0

I have a Vue instance where data property is initialised as an object:

var app = new Vue({
  el: '#app',
  data: {
    obj: { }
  },
  methods: {

  },
  created: function() {
    this.obj["obj2"] = {}
    this.obj["obj2"].count = 0
  },
  mounted: function() {
    setInterval(function() {
      this.obj.obj2.count++
      console.log(this.obj.obj2.count)
    }.bind(this), 1000)
  }
})
<div id="app">
  {{ obj['obj2'].count }}
</div>

And then when the instance is created I add a property to the obj.

However, when I want to display the object's object property count, it shows 0 and is not reactive. If I defined the whole object in the data, it is reactive but I can't define the object in the data because its data depends on an external source - API, that's why it is filled with data in created function.

The only way how I managed to make it show the current count is by forcing updates on the view but I don't think it's the correct solution.

Any suggestions?

enter image description here

5
  • You might be doing the binding wrong, try var self = this; setInterval(function() { self.obj.obj2.count++ console.log(self.obj.obj2.count) }, 1000) Commented Jun 14, 2017 at 10:07
  • @effy No, that's not the problem. It's something with how Vue binds the model to view and object initialization. Commented Jun 14, 2017 at 10:12
  • Have you tried returning a function from data, like so: data: function(){return {obj: {}}}. Commented Jun 14, 2017 at 10:19
  • Please don't put tags in question titles Commented Jun 14, 2017 at 10:23
  • @effy Yea, I have. Commented Jun 14, 2017 at 10:23

1 Answer 1

2

The problem is that Vue can not track completely new properties on its reactive objects. (It's a limitation of JavaScript).

It's described in detail here: https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

The short version is: You have to do

created: function() {
  Vue.set(this.obj, 'obj2', {})
  Vue.set(this.obj.obj2, 'count', 0)
}

or

created: function() {
  Vue.set(this.obj, 'obj2', {
    count: 0
  })
}
Sign up to request clarification or add additional context in comments.

1 Comment

God bless your kind soul! What an intriguing workaround.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.