Skip to content

[vue] vue中data的属性可以和methods中的方法同名吗?为什么? #557

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

[vue] vue中data的属性可以和methods中的方法同名吗?为什么?

Activity

zyronon

zyronon commented on Jul 2, 2019

@zyronon

不能,会报错。

mying01

mying01 commented on Jul 4, 2019

@mying01

Method "xxx" has already been defined as a data property

llccing

llccing commented on Jul 4, 2019

@llccing

@mying01 , 贴一下vue.js代码中的位置

webwhy

webwhy commented on Jul 12, 2019

@webwhy

可以,但eslint不允许你这么做

xiguan-wuge

xiguan-wuge commented on Jul 14, 2019

@xiguan-wuge

会报错(关闭了eslint校验),比如是在使用饿了么组件时,声明一个同名的data 属性和methods方法时,会报错。添加样式的功能没有奏效。
image
image
image
image

binnuo

binnuo commented on Jul 30, 2019

@binnuo

可以,但eslint不允许你这么做

不是啊,就算没有eslint依然会报错的。[Vue warn]: Method "myname" has already been defined as a data property.

RainAley

RainAley commented on Aug 9, 2019

@RainAley

如果真的重名了,data中的变量会覆盖methods中的方法

lukejian003

lukejian003 commented on Aug 14, 2019

@lukejian003

data中的属性和methods方法重名会优先执行data中的属性并且报错

seho-dev

seho-dev commented on Sep 12, 2019

@seho-dev

大家答的都对,但是为什么会先执行data中的呢

Linkontoask

Linkontoask commented on Sep 23, 2019

@Linkontoask

错误会报出来,但是没有中断函数执行,只要不是和 props 同名并且第一个字符不是 _$ ,那么就可以使用 this 访问,然后 observe 数据。
同名的方法被干掉 TypeError: handler.apply is not a function

InterfaceBoy

InterfaceBoy commented on Sep 26, 2019

@InterfaceBoy

肯定是不能同名的了,1、vue语法就会报错,2、如果同名那么你在使用this.XXX的时候是调用方法还是调用变量呢

yangkunxiao

yangkunxiao commented on Mar 7, 2020

@yangkunxiao

不可以。在initState的时候,会对data中的属性、props、methods的属性名进行检查。出现同名立即warn

mingyec

mingyec commented on Mar 28, 2020

@mingyec

为什么会先执行data,是因为组件初始化时的依赖收集会先执行

10 remaining items

Loading
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@llccing@mying01@mingyec@cookingHero

        Issue actions

          [vue] vue中data的属性可以和methods中的方法同名吗?为什么? · Issue #557 · haizlin/fe-interview