Vue / Nuxt-安装:()=> Vs安装:function()

vue.js Vue.js

樱小胖Mandy

2020-03-24

为什么使用() =>function()的结果不同mounted

export default {
  mounted: () => {
    this.socket = 'something'
    console.log('mounted')
  },
  methods: {
    submitMessage() {
      console.log(this.socket) // undefined
    }
  }
}

使用function()

export default {
  mounted: function() {
    this.socket = 'something'
    console.log('mounted')
  },
  methods: {
    submitMessage() {
      console.log(this.socket) // something
    }
  }
}

有任何想法吗?

第3312篇《Vue / Nuxt-安装:()=> Vs安装:function()》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
老丝 2020.03.24

您不应使用箭头功能来定义生命周期挂钩,方法,...(例如mounted: () => this.socket++)。原因是箭头函数绑定了父上下文,因此这将不是您期望的Vue实例,并且this.socket将是未定义的。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android