流程图
    methods流程图.png
    在initState()方法中,调用了initMethods()并传入了当前实例vm和我们撰写的methods。

    1. // src/core/instance/state/initState
    2. export function initState (vm: Component) {
    3. // 省略代码
    4. const opts = vm.$options
    5. if (opts.methods) initMethods(vm, opts.methods)
    6. }

    由函数 initMethods 进行初始化,初始化methods时,只需要循环选项中的methods对象,并将每个属性一次挂载到vm上即可:

    1. // src/core/instance/state/initMethods
    2. function initMethods (vm: Component, methods: Object) {
    3. const props = vm.$options.props
    4. for (const key in methods) {
    5. if (process.env.NODE_ENV !== 'production') {
    6. // 必须为function类型。
    7. if (typeof methods[key] !== 'function') {
    8. warn(
    9. `Method "${key}" has type "${typeof methods[key]}" in the component definition. ` +
    10. `Did you reference the function correctly?`,
    11. vm
    12. )
    13. }
    14. // 命名不能和props冲突。
    15. if (props && hasOwn(props, key)) {
    16. warn(
    17. `Method "${key}" has already been defined as a prop.`,
    18. vm
    19. )
    20. }
    21. // 命名不能和已有的实例方法冲突
    22. // isReserved函数作用是判断字符串是否是以$或_开头
    23. if ((key in vm) && isReserved(key)) {
    24. warn(
    25. `Method "${key}" conflicts with an existing Vue instance method. ` +
    26. `Avoid defining component methods that start with _ or $.`
    27. )
    28. }
    29. }
    30. // 绑定 methods 中的函数到 vm 中
    31. vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm)
    32. }
    33. }

    initMethods 方法首先先声明一个变量props,用来判断methods 中的方法是否和 props发生了重复,然后for…in语句循环methods对象
    在循环中主要逻辑分为两部分:

    • 校验方法是否合法
    • 将方法挂载到vm中

    1. 校验方法是否合法

    • 必须为function类型

      1. // 抛出错误:Method sayHello has type null in the component definition.
      2. // Did you reference the function correctly?
      3. export default {
      4. methods: {
      5. sayHello: null
      6. }
      7. }
    • 命名不和props冲突

      1. // 抛出错误:Method name has already been defined as a prop.
      2. export default {
      3. props: ['name']
      4. methods: {
      5. name () {
      6. console.log('name')
      7. }
      8. }
      9. }
    • 命名不能和已有的实例方法冲突。

      1. // 抛出错误:Method $set conflicts with an existing Vue instance method.
      2. // Avoid defining component methods that start with _ or $.
      3. export default {
      4. methods: {
      5. $set () {
      6. console.log('$set')
      7. }
      8. }
      9. }

      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函数的原因:
    image2020-11-26_18-52-12.png