最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Vue this inside data() factory function - Stack Overflow

programmeradmin2浏览0评论

Can I rely on this used inside data factory function as it was current ponent 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.

Can I rely on this used inside data factory function as it was current ponent 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.

Share Improve this question asked May 2, 2017 at 12:16 ANTARAANTARA 8301 gold badge13 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

Yes, you can rely on this in the data factory function pointing to the ponent, 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 ponent.

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

I think no Perhaps you need

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

评论列表(0)

  1. 暂无评论