vue的属性名称与method的方法名称一样时会发生什么问题?
-
报错
"Method 'xxx' has already been defined as a data property"
键名优先级:props > data > methods
-
报warn,项目可以运行(vue2.5.17)
但data属性会覆盖methods定义的值,报属性已定义警告
props不会覆盖值,但会报属性已定义警告和Prop异常警告 -
[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
-
首先看下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) } }