Vue中methods方法this指向问题


Vue methods方法this指向问题

Vue methods 中不应该箭头函数定义methods函数,因为箭头函数绑定了父级作用域上下文,所以 this 打印出的结果是Window 对象

不使用箭头函数的情况下,this 实际上是指向了一个 Proxy 对象。

vue 内部实际上对methods属性中的方法进行了遍历,将对应的方法且通过bind绑定了this

	//  实例化传入的参数
export function applyOptions(instance: ComponentInternalInstance) {
    // 调用 resolveMergedOptions函数对传入的参数进行解析
    const options = resolveMergedOptions(instance)

	//  定义publicThis指向proxy对象
  const publicThis = instance.proxy! as any
  const ctx = instance.ctx
  
  	// 通过对象解构赋值获取methods属性
   const { methods } = options
  
  	// 判断是否有 methods 属性
  if (methods) {
      // 如果存在,使用for-in 进行遍历 
    for (const key in methods) {
        // 获取key值
      const methodHandler = (methods as MethodOptions)[key]
      	// 使用 isFunction 判断是否 key 是否是一个函数
      if (isFunction(methodHandler)) {
          
        // In dev mode, we use the `createRenderContext` function to define
        // methods to the proxy target, and those are read-only but
        // reconfigurable, so it needs to be redefined here
          
          // 判断是否为dev环境
        if (__DEV__) {
          Object.defineProperty(ctx, key, {
              // 使用bind动态绑定this
            value: methodHandler.bind(publicThis),
            configurable: true,
            enumerable: true,
            writable: true
          })
        } else {
              // 使用bind动态绑定this
          ctx[key] = methodHandler.bind(publicThis)
        }
        if (__DEV__) {
          checkDuplicateProperties!(OptionTypes.METHODS, key)
        }
      } else if (__DEV__) {
          // 如果key 不是函数,dev环境下控制台打印警告
        warn(
          `Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
            `Did you reference the function correctly?`
        )
      }
    }
  }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM