Vuejs 箭头函数不触发第二条语句

Vuejs Arrow Function not triggering second statement

我在 Vuejs 组件的方法部分使用 lambda 表达式。

例子如下 我触发 alertyou() 并收到警报,单击确定。然后在 vue 开发者工具中我看到 this.activated 变成 true.

export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      activated: false
    }
  },
  methods: {
      alertme: () => { alert('Clicked'); this.activated = false; },
      alertyou() {
        alert('Alert You');
        this.activated = true
      }
  }
}

但是,当我单击触发 alertme lambda 的按钮时。我收到警报消息,单击确定。但是 this.activated 保持正确!

这是怎么回事,这是对 lambda 的限制吗?每个 lambda 只能触发一个语句吗?或者这是否必须在触发警报后处理范围?

alertme: () => { alert('Clicked'); this.activated = false; } 更改为 alertme() { alert('Clicked'); this.activated = false; }。你可以看到一个工作示例 here

What is going on here is this a limitation with lambdas? Can you only trigger one statement per lambda? Or does this have to deal with scope once an alert is fired?

两者都不是。

箭头函数将 this 绑定到创建箭头函数时的上下文。在这种情况下,this 不是 vue 实例。大概是window

使用 function 关键字(或 ES6 对象 shorthand 样式)在对象上声明的函数通常会将 this 绑定到声明该函数的对象。

这就是为什么您可以在 alertyou 上访问 this.activated 而不能在 alertme

上访问的原因

您需要使用与 alertyou 相同的语法来声明 alertme 方法。