Vue component data communication methods are many, this article summarizes all the ways together to say, the level is limited, wrong words, welcome to correct.
Component communication is when one component gets data or methods from another component.
Take a look at all the ways, eight of them:
props
/$emit
– Specific use moderef
/$refs
– Specific use modeslot
Scope of -Specific use modeeventBus
– Specific use modevuex
– Specific use mode$attrs
/$listeners
– Specific use mode$parent
/$children
– Specific use modeprovide
/inject
– Specific use mode
So many ways, how to choose.
First, there is a big, principled judgment about whether or not you are encapsulating components.
Not encapsulating components, just using components in general
Using components in general, rather than encapsulating them, is usually done in the following way:
- props/$emit
- ref/$refs
- Scope of slot
- eventBus
- vuex
Continue, is not a parent-child component.
Parent and child components:
- First,
prop/$emit
, combined with grammatical sugar if necessary.sync
andv-model
. - Only if you want to display the data of a child component/third party component or execute its utility methods, consider the option
ref/$refs
- If slot-scoped data is provided internally by a child component or a third party component, this is taken into account
slot
way
Across components: Data is no longer miscellaneous with eventBus, complex with Vuex
Encapsulating components
Encapsulate components, or even nest components
- Encapsulating third-party components or some simple form components can be considered
$attrs/$listeners
- The internal nesting level of a component is uncertain, and descendants of components that want data from their ancestors can be considered
provide/inject
- Component internal nested relationship is clear, and only display the data of the upper and lower components or implement its tool methods, can be considered
$children/$parent
practice
You can use this to practice writing the core logic of the el-form by hand