Vue methods 用箭头函数取不到 this

2020-01-04 08:10:41

参考地址 Vue methods 用箭头函数取不到 this

首先,看文档 http://cn.vuejs.org/api/#methods

实例方法。实例可以直接访问这些方法,也可以用在指令表达式内。方法的 this 自动绑定到实例。
在vue的methods的this是自动绑定的

然后见代码:https://github.com/vuejs/vue/...

function initMethods (vm: Component) {  const methods = vm.$options.methods  if (methods) {    for (const key in methods) {
      vm[key] = methods[key] == null ? noop : bind(methods[key], vm)      if (process.env.NODE_ENV !== 'production' && methods[key] == null) {
        warn(          `method "${key}" has an undefined value in the component definition. ` +          `Did you reference the function correctly?`,
          vm
        )
      }
    }
  }
}

你用箭头函数,会返回一个绑定当前执行上下文中的this,而且这个this,不可再切换更改了。你此处绑定的 this 是当前函数体内的this,严格模式下为undefined;



更多讨论内容,点开文章开头的链接


  • 2018-09-27 10:04:11

    jquery ajax超时设置

    原来ajax可以设置超时时间,那么简单,ajax还有更多功能,虽然不怎么用它,有时候还挺好用。

  • 2018-10-10 14:29:01

    php header()函数设置页面Cache缓存

    ​ header()函数在php的使用很大,下面我来介绍利用它实现页面缓存的一些方法,但使用header前必须注意,在它之前不能任何输出,包括空格。