Vue this 里面的 data() 工厂函数

Vue this inside data() factory function

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

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

简单测试,这里thisVueComponent实例,问题是框架是否允许这样使用。

我认为没有 或许你需要

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

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

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

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

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