This blog is a personal self-study record, if there is any deficiency, please criticize and correct.
Official documentation:.sync modifier
What does Sync do
Sync is a syntactic sugar; When a child component changes the value of a prop, the change is synchronized to the parent component.
Explain in detail
Usage scenarios
- Use sync when a child component needs to change the state of the parent component by modifying a prop passed by the parent component
function
- It is a two-way binding of prop values between parent and child components
Real life examples
I need to get a loan from the bank, and normally all the money is in the bank at this point, so I need to get a loan from the bank, and then I can withdraw my money from the bank and use it;
Wouldn’t it be robbery if I just went to the bank to withdraw money without applying?
Similarly, the process of component transfer is equivalent to the bank telling me that there is so much money I can borrow, instead of telling me to go to the vault and withdraw the money, I tell the bank how much I want to borrow, and then I tell the bank how much is left
Code sample
Child.vue (child component)
<template> <div class="child"> {{money}} <! <button @click="$emit('update:money', <span> </span> </div> </template> <script> export default {props: ["money"]}; </script>Copy the code
Parent. Vue (Parent component)
<template> <div class="app"> app. vue I have {{total}} <hr> <! -- Grammar sugar --> <! -- <Child :money.sync="total"/> --> <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>Copy the code
conclusion
In summary:.sync is the syntactic sugar for event binding