Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
haizhilin2013 opened this issue Jun 22, 2019 · 7 comments
Labels
vue vue

Comments

@haizhilin2013
Copy link
Collaborator

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

@haizhilin2013 haizhilin2013 added the vue vue label Jun 22, 2019
@dengBox
Copy link

dengBox commented Jun 28, 2019

报错,语法错误

@April-Zheng
Copy link

报错

@tsejx
Copy link

tsejx commented Jul 7, 2019

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

键名优先级:props > data > methods

@zejunking
Copy link

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

@censek
Copy link

censek commented Oct 22, 2019

[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

@JaniceDong
Copy link

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

@duzouli
Copy link

duzouli commented Mar 28, 2020

首先看下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)
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
vue vue
Projects
None yet
Development

No branches or pull requests

8 participants