Skip to content
Advertisement

Is it possible to discard data errors in a Vue instance?

I will have a lot of variables in my Vue instance modified via API calls. Their initial value is not important.

I was hoping there would be a way not to define them upon the instantiation of the vm but this does not work:

vm = new Vue({
  el: "#app",
  data: {}
});
vm.number = 3
<div id="app">
  {{ number }}
</div>

If I replace data: {} by data: { number: null } the code runs fine.

What I would like to avoid is to have a litany of such declarations – is there a way not to declare the data variables upon instantiation?

Advertisement

Answer

Not really.

The docs explain how reactivity works in Vue as follows:

When you pass a plain JavaScript object to a Vue instance as its data option, Vue will walk through all of its properties and convert them to getter/setters using Object.defineProperty.

The getter/setters are invisible to the user, but under the hood they enable Vue to perform dependency-tracking and change-notification when properties are accessed or modified.

Due to the limitations of modern JavaScript (and the abandonment of Object.observe), Vue cannot detect property addition or deletion.

So basically in plain terms, in order for a data value to be reactive and thus be updated when your API call returns, the property must be present from the time of instantiation because Vue cannot detect addions or deletions.

That being said, you can sort of fake it as was suggested by @gskema by using a placeholder object and attaching your properties to that object. These changes will indeed be picked up by Vue.

So you could do:

data: {
  api: null
}

and then attach your api values to that api property when they are returned, and finally just reference all the data by api.number etc.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement