Application scenarios
- Is used when the parent component passes a value and the child component wants to modify the data. Its principle is to use EventBus, the child component triggers the event, the parent component responds to the event and realizes the data update, avoiding the child component to directly modify the content sent by the parent component. (VUE has a warning if the child operates directly)
To take a practical example: Normally, the father gets the money. The son asks for the money by telling the father to use it, and then the father takes the money out of the son and gives it to him. If the child component directly operates on the value passed by the parent component, it is equivalent to the son taking the money without notifying the father, which is tantamount to stealing money, which is not reasonable.
In fact, the parent component passes the value, which is equivalent to the father telling the son, I have some money to use, rather than the child component directly manipulating the value. Tell me how much you want to use, and then tell me how much will be left over.
With this logic in mind, here’s an example:
The complete code
Child.vue (child component)
<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
Parent. Vue (Parent component)
<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
With the.sync modifier, you can place the<Child :money="total" v-on:update:money="total = $event"/>
Modified to:<Child :money.sync="total"/>
$emit(‘ Update :money’, money-100) is used by the child component to send $emit(‘ Update :money’, money-100) to the parent component. The parent component receives the modified value via $event.
Note that the v-on:update:money event must be written as update:mondy. Update is the syntax specified by VUE, and money is the property of the bound event. To make it official
The child component must also trigger the response with the ‘Update :money’ event name
<button @click="$emit('update:money', money-100)">
Copy the code