'When to use props and when to use $attrs in Vue
In Vue we can use props, and also we can use $attrs.
When it is better to use props and when it is better to use $attrs?
Can we always use $attrs for those that we are not changing their value and just use props for those that we are changing their value?
Solution 1:[1]
In most cases you should use props, it doesn't matter if they are bound to parent properties or just receiving a static value, because that props are a part of the component identity, if you browse any vue component in npm or github you'll find a section dedicated to props, the use of $attrs is explained here :
A non-prop attribute is an attribute that is passed to a component, but does not have a corresponding prop defined.
While explicitly defined props are preferred for passing information to a child component, authors of component libraries can’t always foresee the contexts in which their components might be used. That’s why components can accept arbitrary attributes, which are added to the component’s root element.
For example, imagine we’re using a 3rd-partybootstrap-date-inputcomponent with a Bootstrap plugin that requires adata-date-pickerattribute on the input. We can add this attribute to our component instance:<bootstrap-date-input data-date-picker="activated"></bootstrap-date-input>
And thedata-date-picker="activated"attribute will automatically be added to the root element ofbootstrap-date-input
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Boussadjra Brahim |
