- When I introduced a Switch subcomponent into a component, I found that the outside world could not know whether the current state was on or off, and the outside world could not enter the original state.
How to do?
- Add value attribute, add input event
<Switch :value="xxx" @input="xxx = $event" />
- Enable the Switch subcomponent to accept value using props
- with
context.emit('input', yyy)
Make the Switch issue an input event with yyy being the latest value, which will be treated as $event
Supplementary: Vue3 new V-model usage
-
The V-Model simplifies “father-child data communication”. Here is a note that accompanies my previous article: V-Model
-
First, it should not be called an “input” event, it should be the same as the props name. For example, the ‘input’ event in the code above should only be called an ‘Update :value’ event
- Let’s keep simplifying
@update:value="xxx = $event "
Delete,:value
Plus the V-model, plus the v-modelv-model:value
Equivalent to the original code.
conclusion
Using the V-Model greatly simplifies data communication between parent and child components
- Requirements: The property name is arbitrary, let’s say x; The event name must be “Update :x”
- Effect:
<Switch:value="y" @update:value="y = $event"/>
Shorthand for<Switch v-model:value="y"/>
- This is a big change from Vue2 to Vue3, with the new V-Model replacing the previous V-Model and.sync
Another difference between Vue2 and Vue3 is that Vue3 has been addedcontext.emit
, the role andthis.$emit
The same.
- The difference between:
insetup(){}
The need for acontext.emit
.
insetup(){}
Can’t usethis.$emit
, because this is not the current instance, but can bemethods:{}
In use.