javascript - VueJS : Difference of data() { return {} } vs data:() => ({ })

标签 javascript vue.js vuejs2 arrow-functions

我很好奇这两个数据函数,这两者之间有什么区别吗?

我平时看到的是

data () {
  return {
    obj
  }
}

还有我通常使用的 ES6 胖箭头 (=>)

data:()=>({
  obj
})

最佳答案

在你的具体例子中没有区别,但是这两个符号之间有一个非常重要的区别,特别是当涉及到 Vue.js 时:this不会在箭头函数中反射(reflect) vue 实例。

所以如果你有这样的事情:

export default {
    props: ['stuffProp'],
    data: () => ({
      myData: 'someData',
      myStuff: this.stuffProp
    })
}

它不会像您预期的那样工作。 this.stuffProp 不会获得 stuffProp 属性的值(请参阅下文了解更多原因)。

修复

将箭头函数更改为,或者(ES6/EcmaScript 2015 表示法):

export default {
    props: ['stuffProp'],
    data() {                                   // <== changed this line
      return {
        myData: 'someData',
        myStuff: this.stuffProp
      }
    }
}

Or to(常规,ES5 及之前,表示法):

export default {
    props: ['stuffProp'],
    data: function() {                           // <== changed this line
     return {
        myData: 'someData',
        myStuff: this.stuffProp
      }
    }
}

原因

在声明 Vue 方法时不要使用箭头函数 (() => {})。他们从当前范围(可能是 window)中获取 this,并且不会反射(reflect) Vue 实例。

来自API Docs :

Note that you should not use an arrow function with the data property (e.g. data: () => { return { a: this.myProp }}). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.myProp will be undefined.

关于javascript - VueJS : Difference of data() { return {} } vs data:() => ({ }),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48980865/

相关文章:

typescript - 元素 UI 树数据未随 Vue 更新

vue.js - Vue 双向 prop 绑定(bind)

javascript - highcharts-vue 给出有关 highcharts HTML 元素的错误

javascript - 如何使用javascript获取本地计算机中的默认打印机名称?

javascript - 如何从我的 vue 路由器中的商店/状态访问此变量?

javascript - ajax xml 加载后 jQuery 切换不起作用

javascript - Vue router 路由的安全性

laravel - Vue.js 路由器 View 没有组件?

javascript - $timeout 中的 "Controllers as"语法

javascript - 用户选择从今天开始 10 年的日期 jquery datepicker