The child component of vUE cannot use the parent component’s data directly, so we need to use prop to pass the data. However, can the child component directly modify the parent component’s data?
Following the example in the official documentation: Listening for child component Events we learned that VUE uses a custom event system to help us modify data on the parent component.
It has an API, $emit, through which we can modify the data on the parent component on the child component.
- Fires a custom event on a child component and passes a custom event
Writing:
@click="$emit('something')"
Copy the code
- Listen for this custom event using V-on on the children of the parent component
<child :num='num' v-on:something='num += 1' /> // This num is the data above the parent component
Copy the code
This allows the child to modify the data on the parent.
Let’s first examine the $emit API
$emit
$emit accepts two arguments:
{string} eventName triggers events on the current instance. [...args] Additional arguments are passed to the listener callback.Copy the code
We need to call $emit on the template of the child component and then listen for this custom event on the parent component. Additional parameters are passed to the parent component for use when executed.
usage
. props: [' MSG '], // when clicked, an "update:n" event is triggered, <button @click="$emit('update:n',n-1)"> < {{n}} </button>Copy the code
Update :n ($event); update:n ($event); / / $event is child components of n - 1 < child: n = 'MSG' v - on: update: n = "n = $event" > < / child >Copy the code
The sample code
Vue.component('child', { props: ['msg'], template: ` < div > < hr > I am a child component < button @ click = "$emit (' update: n, MSG - 1)" > subcomponents click {{MSG}} < / button > < / div > `}) new Vue ({el: '.app1', data() { return { n: 100 } }, template: Father ` < div > component n: {{n}} < child: MSG = 'n' v - on: update: n = 'n = $event' > < / child > < / div > `})Copy the code
The sync usage
The above code takes two steps:
The word component on the parent listens for the custom event and sets the property value n equal to the $event passed in
v-on:update:n='n=$event'
2. The code in the sub-component is clicked to trigger a custom event and pass a parameter, MSG -1
@click="$emit('update:n',msg-1)"
So, can we simplify the code?
Vue was kind enough to do the work for us, which is the.sync modifier
Usage:
The parent component tells the child to synchronize the MSG passed to it with the n on the parent component, allowing it to modify
<child :msg.sync='n'></child>
Copy the code
The code on the child component reads:
< button @ click = "$emit (' update: MSG, MSG - 1)" > subcomponents click {{MSG}} < / button >Copy the code
Note that eventName can only be used as a prop property passed in from update:.