Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue this inside data() factory function

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.

like image 510
ANTARA Avatar asked Jul 24 '26 20:07

ANTARA


1 Answers

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
    } 
}
like image 82
Bert Avatar answered Jul 27 '26 08:07

Bert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!