Skip to content

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

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

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

Activity

dengBox

dengBox commented on Jun 28, 2019

@dengBox

报错,语法错误

April-Zheng

April-Zheng commented on Jul 1, 2019

@April-Zheng

报错

tsejx

tsejx commented on Jul 7, 2019

@tsejx

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

键名优先级:props > data > methods

zejunking

zejunking commented on Aug 14, 2019

@zejunking

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

censek

censek commented on Oct 22, 2019

@censek

[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

JaniceDong commented on Mar 13, 2020

@JaniceDong

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

duzouli

duzouli commented on Mar 28, 2020

@duzouli

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@zejunking@JaniceDong@tsejx@April-Zheng

        Issue actions

          [vue] vue的属性名称与method的方法名称一样时会发生什么问题? · Issue #465 · haizlin/fe-interview