代码之家  ›  专栏  ›  技术社区  ›  Run

Vue/Nuxt-装载:()=>Vs装载:函数()

  •  5
  • Run  · 技术社区  · 9 年前

    为什么使用结果不同 () => 和 function() 在里面 mounted

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

    使用 函数() :

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

    有什么想法吗?

    1 回复  |  直到 9 年前
        1
  •  11
  •   Quoc-Anh Nguyen    9 年前

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

    推荐文章