3

Is there a difference between the following? I've seen examples doing both and am unsure why you would choose one over the other.

Vue.component('test', {

        data() {
           return { myDataA: 10 };
        }

        //vs

        created() {
           this.myDataB = 10;
        }
    }

2 Answers 2

5

Variables set in created() on this will not be reactive. In order for them to be reactive, you must define them in the object returned by data().

Example (note how the text does not change in the output): https://jsfiddle.net/oyf4quyL/

Sign up to request clarification or add additional context in comments.

4 Comments

OK, that makes sense. Thanks.
This isn't entirely true. This is certainly true of root-level data properties, but not for nested properties. Vue.set(object, key, value) can be used to define new reactive properties for nested objects in data. I feel that this distinction is important. More generally, you should only set properties in created() or another lifecycle hook if you're accepting a prop and want to have a local copy to mutate, and even then any root-level properties need to be defined prior to initialization.
@B.Fleming Good suggestions. FYI, prop values can be referenced in the data method, so I always set local copies of prop data directly in the data method, not in created.
@B.Fleming Thanks, I've edited my answer to be more clear.
1

in a component, there are three places where you can define you data:

  1. data properties
  2. computed properties
  3. props

the created property is lifecycle hook in Vue. what this means, is that the Vue will run this function when the component is created. there are also other lifecycle hooks in Vue you can use, like mounted or beforeMount or beforeCreate and etc.

now with this in mind, let's answer your question.

when you define myDataA in data property, Vue will automatically create some "watchers" for this data property, so anytime that you set a new value to myDataA, anywhere that is using it, will be called again. but when you define a property directly on Vue instance (this), you will lose this "watchers" feature. (which by the way is just some getters and setters!)

so as i said, the best way and the correct way to define a data property is on any of the three places that i mentioned, based on your need. (because each of them has different use-cases that the others).

Comments

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.