Vue.js '的不同行为;这';在VueJs中使用箭头函数

Vue.js '的不同行为;这';在VueJs中使用箭头函数,vue.js,vue-component,this,arrow-functions,strict,Vue.js,Vue Component,This,Arrow Functions,Strict,好的,我想谈三个案例。我知道箭头函数有词法作用域,这将向外传播,直到找到匹配项。然而,在某些情况下,这些行为对我来说没有意义,因此一些解释将是非常好的 1。在单个文件组件的方法中 //HelloWorld.vue <template> <div class="hello"> <h1>{{ msg }}</h1> <button @click="nonArrow">click m

好的,我想谈三个案例。我知道箭头函数有词法作用域,这将向外传播,直到找到匹配项。然而,在某些情况下,这些行为对我来说没有意义,因此一些解释将是非常好的

1。在单个文件组件的
方法中

//HelloWorld.vue

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <button @click="nonArrow">click me</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  methods: {
    nonArrow() {
      console.log(this);
    },
    arrow: () => {
      console.log(this);
    }
  }
}
</script>
noArrow()。为什么在前面的示例中没有引用
窗口

3。使用严格模式

methods: {
    noArrow() {
        console.log(this);
    },
    arrow: () => {
        "use strict";
        console.log(this);
    }
}
在第二个示例中,如果我在方法内部使用带箭头函数的严格模式,它仍然输出
窗口
对象,而在严格模式外部定义的普通箭头函数将控制日志
未定义
。这是怎么回事


不要在选项属性或回调上使用箭头函数,例如created:()=>console.log(this.a)或vm.$watch('a',newValue=>this.myMethod())。由于arrow函数没有this,因此它将被视为任何其他变量,并通过父作用域进行词汇查找,直到找到为止,通常会导致错误,例如Uncaught TypeError:无法读取undefined或Uncaught TypeError的属性:this.myMethod不是函数

你不应该使用箭头功能。请参考此链接


我知道我不应该使用箭头功能。我只是想了解这些差异的原因。由于箭头函数没有
this
this
将被视为任何其他变量,并通过父作用域进行词汇查找,直到找到为止。是的,但是在第一个示例中,词汇作用域解析到哪里?为什么它显示未定义?它与哪个“this”匹配?它基本上意味着arrow函数从其上下文中获取
this
,这意味着如果您试图从Vue组件上的arrow函数内部访问
this
,您将得到一个错误,因为
this
不存在!好的,那么箭头函数的上下文是什么?它包含在
方法
对象中。
methods: {
    noArrow() {
        console.log(this);
    },
    arrow: () => {
        "use strict";
        console.log(this);
    }
}