3

Can I rely on this used inside data factory function as it was current component object instance? I couldn't find in docs what this is in data().

data() {
  return {
    results: [],
    apiResource: this.$resource('url...'), // <-- this used here
    loading: true,
  }
},

Simple test shows that this is VueComponent instance here, but the question is if the framework allows using it this way.

ANTARA
  • 810
  • 1
  • 13
  • 20

2 Answers2

6

Yes, you can rely on this in the data factory function pointing to the component, depending on how you define the function. It's the primary way of initializing local data with values from properties, for example.

props:["value"],
data(){
    return {
         localValue: this.value
    } 
}

If, however, you defined your data function with an arrow function, this will not be the component.

props:["value"],
data: () => { 
    // 'this' is NOT the component 
    return { 
        localValue: this.value // results in undefined
    } 
}
Bert
  • 80,741
  • 17
  • 199
  • 164
  • I've found similar example in [docs](https://vuejs.org/v2/guide/components.html#One-Way-Data-Flow) proving you're right. I'm still curious in what moment of component lifecycle `data()` is called. It's crucial to know what is available via `this` pointer then (props, plugins, mixins, rendered template etc). – ANTARA May 03 '17 at 13:44
  • @ANTARA The code isn't terribly difficult to follow. When a new Vue is created, it calls the `_init` method. The state is initialized between `beforeCreate` and `created`. https://github.com/vuejs/vue/blob/dev/dist/vue.js#L3964 – Bert May 03 '17 at 15:10
  • Does the factory function mean that in this case if `this.value` were an object, that a copy is made so that changing the data copy wouldn't change the props? – writofmandamus Nov 02 '17 at 21:22
  • @writofmandamus Javascript objects are passed by reference, so, no. – Bert Nov 02 '17 at 21:30
  • @Bert Right, but then why would the Vue creators enforce these factory function methods? I think this discussion relates to it? https://github.com/vuejs/vue/issues/1032 – writofmandamus Nov 02 '17 at 23:40
  • 1
    @writofmandamus The data factory function is so you *can* have separate component data, otherwise all instances of the same component would share the same data. Objects being passed by reference is something you can take advantage of or avoid at your choice. You can always choose to make a copy of `this.value`, or not depending on your needs. – Bert Nov 02 '17 at 23:59
0

I think no Perhaps you need

data() {
  return {
    results: [],
      set apiResource(v){},
      get apiResource()( return this.$resource('url...')), // <-- this used here
    loading: true,
  }
},
Stilet
  • 92
  • 2