【问题标题】:Vue JS fat arrow method does not bind Vue instance [duplicate]Vue JS胖箭头方法不绑定Vue实例[重复]
【发布时间】:2020-04-06 12:32:18
【问题描述】:

您好,我正在尝试在 vuex 组件文件中使用粗箭头函数作为方法:

methods : {
    method_1 : () => {console.log(this)}
}

this 返回 undefined,但如果我使用 function() { console.log(this) } 它会返回当前的 vue 实例。

这是为什么?

【问题讨论】:

    标签: vue.js ecmascript-6


    【解决方案1】:

    这是因为this 关键字在经典函数和箭头函数中的作用不同。

    Vue.js 假设您将使用经典函数,因此他们可以控制 this 的值(这是 Vue 实例)

    你需要做的是:

    method_1 : function() { console.log(this) }
    

    method_1() { console.log(this) }
    

    但如果需要this 关键字,则不能使用箭头函数

    【讨论】:

      猜你喜欢
      • 2017-10-31
      • 1970-01-01
      • 2020-11-07
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 2016-02-11
      • 1970-01-01
      相关资源
      最近更新 更多