fe-interview icon indicating copy to clipboard operation
fe-interview copied to clipboard

[vue] vue的属性名称与method的方法名称一样时会发生什么问题?

Open haizhilin2013 opened this issue 7 years ago • 7 comments

[vue] vue的属性名称与method的方法名称一样时会发生什么问题?

haizhilin2013 avatar Jun 22 '19 21:06 haizhilin2013

报错,语法错误

dengBox avatar Jun 28 '19 09:06 dengBox

报错

April-Zheng avatar Jul 01 '19 02:07 April-Zheng

报错 "Method 'xxx' has already been defined as a data property"

键名优先级:props > data > methods

tsejx avatar Jul 07 '19 12:07 tsejx

报warn,项目可以运行(vue2.5.17) 但data属性会覆盖methods定义的值,报属性已定义警告 props不会覆盖值,但会报属性已定义警告和Prop异常警告

zejunking avatar Aug 14 '19 11:08 zejunking

[Vue warn]: Method "xxx" has already been defined as a data property. [Vue warn]: Error in mounted hook: "TypeError: this.xxx is not a function" TypeError: this.xxx is not a function

censek avatar Oct 22 '19 00:10 censek

@tsejx 你说的这个键名优先级顺序确定是正确的嘛

JaniceDong avatar Mar 13 '20 02:03 JaniceDong

首先看下initState(vm)方法的定义:

export function initState(vm) {
  ...
  const opts = vm.$options
  if(opts.props) initProps(vm, opts.props)
  if(opts.methods) initMethods(vm, opts.methods)   // 主要作用是将methods内的方法挂载到this下
  if(opts.data) initData(vm)
  ...
  if(opts.computed) initComputed(vm, opts.computed)
  if(opts.watch && opts.watch !== nativeWatch) {
    initWatch(vm, opts.watch)
  }
}

再看initMethods (vm, methods):

function initMethods(vm, methods) {
  const props = vm.$options.props
  for(const key in methods) {
    
    if(methods[key] == null) {  // methods[key] === null || methods[key] === undefined 的简写
      warn(`只定义了key而没有相应的value`)
    }
    
    if(props && hasOwn(props, key)) {
      warn(`方法名和props的key重名了`)
    }
    
    if((key in vm) && isReserved(key)) {
      warn(`方法名已经存在而且以_或$开头`)
    }
    
    vm[key] = methods[key] == null
      ? noop  // 空函数
      : bind(methods[key], vm)  //  相当于methods[key].bind(vm)
  }
}

duzouli avatar Mar 28 '20 07:03 duzouli