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;



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


  • 2020-12-07 16:17:53

    nodejs用redis实现队列操作

    其实nodejs实现队列的方式又很多中,也有很多开源的插件和队列数据库可以使用,但是呢,如果我们一个简单的项目,完全可以使用redis来实现队列, 这样再不增加技术难度的同事,我们也就可以完美的实现一个队列

  • 2020-12-07 22:02:44

    intellij idea远程开发的几个想法

    我之前是用idea上面自带的stfp来做的本地开发同步到linux服务器编译,但是我发现这个如果多个客户端同时开发,或者多个同事一起开发,服务器上的就不能更新到本地。是不能增量更新到本地,必须全部下载,比对下载也行,但是工程量打了就特别慢。

  • 2020-12-07 22:06:13

    System Extension Blocked - warning

    After upgrading your macOS computer to High Sierra 10.13.4 or higher (starting in April 2018), you may see a message about a System Extension Blocked. At Williams we have seen this warning appear for these programs:

  • 2020-12-08 08:57:12

    win10上使用win-sshfs

    首先在GitHub上下载DokanSetup-1.0.5.1000和WinSSHFS-1.6.1.13-devel 注意:Dokan不能使用最新的版本,得使用1.0.5版本。要不win-sshfs会报Dokan版本错误的问题。(win10版本)

  • 2020-12-08 11:51:54

    Ubuntu安装Node.js和npm

    Node.js是基于Chrome的JavaScript构建的跨平台JavaScript运行时环境,npm是Node.js的默认程序包管理器,也是世界上最大的软件注册表。本篇文章展示了三种在Ubuntu 20.04服务器上安装Node.js和npm的方法。