Vue this inside data() 工厂函数

ANT*_*ARA 3 javascript vue-resource vuejs2

我可以依赖this使用的内部数据工厂函数,因为它是当前组件对象实例吗?this我在文档中找不到data().

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

简单的测试表明这thisVueComponent这里的实例,但问题是框架是否允许以这种方式使用它。

Ber*_*ert 6

是的,您可以依赖this数据工厂中指向组件的函数,具体取决于您定义该函数的方式。例如,这是使用属性值初始化本地数据的主要方式。

props:["value"],
data(){
    return {
         localValue: this.value
    } 
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您使用箭头函数定义数据函数,则该数据函数this不是组件。

props:["value"],
data: () => { 
    // 'this' is NOT the component 
    return { 
        localValue: this.value // results in undefined
    } 
}
Run Code Online (Sandbox Code Playgroud)