流程图
在initState()方法中,调用了initMethods()并传入了当前实例vm和我们撰写的methods。
// src/core/instance/state/initStateexport function initState (vm: Component) {// 省略代码const opts = vm.$optionsif (opts.methods) initMethods(vm, opts.methods)}
由函数 initMethods 进行初始化,初始化methods时,只需要循环选项中的methods对象,并将每个属性一次挂载到vm上即可:
// src/core/instance/state/initMethodsfunction initMethods (vm: Component, methods: Object) {const props = vm.$options.propsfor (const key in methods) {if (process.env.NODE_ENV !== 'production') {// 必须为function类型。if (typeof methods[key] !== 'function') {warn(`Method "${key}" has type "${typeof methods[key]}" in the component definition. ` +`Did you reference the function correctly?`,vm)}// 命名不能和props冲突。if (props && hasOwn(props, key)) {warn(`Method "${key}" has already been defined as a prop.`,vm)}// 命名不能和已有的实例方法冲突// isReserved函数作用是判断字符串是否是以$或_开头if ((key in vm) && isReserved(key)) {warn(`Method "${key}" conflicts with an existing Vue instance method. ` +`Avoid defining component methods that start with _ or $.`)}}// 绑定 methods 中的函数到 vm 中vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm)}}
initMethods 方法首先先声明一个变量props,用来判断methods 中的方法是否和 props发生了重复,然后for…in语句循环methods对象
在循环中主要逻辑分为两部分:
- 校验方法是否合法
- 将方法挂载到vm中
1. 校验方法是否合法
必须为function类型
// 抛出错误:Method sayHello has type null in the component definition.// Did you reference the function correctly?export default {methods: {sayHello: null}}
命名不和props冲突
// 抛出错误:Method name has already been defined as a prop.export default {props: ['name']methods: {name () {console.log('name')}}}
命名不能和已有的实例方法冲突。
// 抛出错误:Method $set conflicts with an existing Vue instance method.// Avoid defining component methods that start with _ or $.export default {methods: {$set () {console.log('$set')}}}
2. 将方法挂载到vm中 ```javascript // 空函数 function noop () {}
vm[key] = typeof methods[key] !== ‘function’ ? noop : bind(methods[key], vm)
```
判断了我们定义的methods是不是function类型,如果不是则赋值为一个noop空函数,
如果是则把这个方法进行bind绑定,其中传入的vm为当前实例。
这样做的目的是为了把methods方法中的this指向当前实例,这样我们就能在methods方法中通过this.xxx的形式很方便的访问到props、data以及computed等与实例相关的属性或方法。
这也是我们为什么不能使用箭头函数来定义methods函数的原因:

