As you can see from the Vue documentation, because we often have situations where we need to modify external elements in a child component, we can’t do it ourselves, we have to tell the parent component to do it. The $emit event is bound to the child component and listens to the child component in the parent component.

Here’s an example:

The father gives the son money, the son wants to spend money, how should do?

A: The son calls (triggers) the father and says: I need to spend money

This is an example of a child component not being able to modify the data itself, but having to trigger an event to tell the parent component to modify the data.

Child. Vue:

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

In the Child component, there is an external data money, which starts with money, and a button called Spend money, which is bound to an ‘Update: Money’ event, where you click the button, spend 100, and display the remaining money money-100.

App.vue:

<template> <div class="app"> app. vue I now 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

The effect appears as follows:

Click “Spend money”

$event = ‘uoDate :money’; $event =’ uoDate: Money ‘; $event = ‘uoDate: Money’;

Because this is so common, Vue encapsulates a modifier –.sync. Use method:

<Child :money.sync="total"/>

Is equivalent to

<Child :money="total" v-on:update:money="total = $event"/>

So the.sync modifier is a syntactic sugar. From this we can see the three rules of Vue:

  1. Components cannot be modifiedpropsExternal data
  2. $eventCan trigger events and pass parameters
  3. $eventAccess to$emitThe parameters of the