meaning

  • When we want the modification to pass in the child componentpropsData in a bound external component,VueIt does not allow us to modify directly in the child component, the child component does not have the right to modify the parent component data.
  • We can useEventBusThe center of the incidentvueThe example contains$emitInterface to trigger events, so used in child components$emit()To fire the event and pass in the modified value as a parameter.
  • Vue saves the parameters passed to$eventIn, the parent responds to the event and passes$eventTo realize the update of data.

The sample

The parent component

<template> <div class="app"> I have {{total}} <hr> <Child :money="total" V-on :update:money="total = $event"/> </div> </template> <script> import Child from "./Child.vue"; export default { data() { return { total: 10000 }; }, components: { Child: Child } }; </script> <style> .app { border: 3px solid red; padding: 10px; } </style>Copy the code

Child components

<template> <div class="child"> {{money}} <button @click="$emit('update:money', <span> </span> </button> </div> </template> <script> export default {props: ["money"]}; </script> <style> .child { border: 3px solid green; } </style>Copy the code

We can use the.sync modifier to simplify the parent component’s code:

This is a grammar sugar.