I'm working on a Vue
project. With the eslint
's requirement, I cannot name the props with camel case
and it will report a warning Attribute ':clientId' must be hyphenated. eslint vue/attribute-hyphenation
is required to use kekab
case instead. For example,
<GranfFather :client-id="clientId" v-bind="$attrs">
<Father>
<GrandSon />
</Father>
</GrandFather>
I need to access the property in the <GrandSon />
component. Generally, I'd like to name the property as clientId
, but due to the eslint
's requirement of the company, I can only name it as client-id
otherwise it will report a warnning. So, if I want to access this property, the only method I come up with is use this.$attrs["client-id"]
. But I'm wondering how could I access this property via this.$attrs.clientId
or in a similar method?
when I use this.$attrs
in <GrandSon />
component, it print
{ client-id: "xxxxxx"}
Is this mean I can only client-id
via this.$attrs["clientId"]
?
What I want is access client-id
just by using this.$attrs.clientId
.
CodePudding user response:
There is a difference between props and attributes.
A prop is supposed to be specified in component props
, it is normalized to camel case and received only by a component that a prop was provided to.
Attributes aren't normalized and can fall through components that are used as root elements. This behaviour is determined by inheritAttrs
property in components. It is commonly used to provide HTML attributes to root HTML elements, but can also be used to provide a prop to nearest nested components that accept it.
If GrandSon
is supposed to receive clientId
prop, it needs to be declared in the component in props
. Although it apparently can receive a prop as a fallthrough attribute from GrandFather
in this case, it's preferable to explicitly provide it as <GrandSon :client-id="clientId">
in order for it to not depend on a specific hierarchy of root elements.