.sync是父子组件之间传递信息时可用的一个语法糖。
我们来举个例子,
App.vue
<template><div class="app">App.vue 我现在有{{total}}<Child :money="total" v-on:我要花钱="total = $event" /></div></template><script>import Child from "./Child.vue"export default{data(){return {total:10000}},components:{Child:Child}}</script>
Child.vue
<template><div class="child">{{money}}<button @click="$emit('我要花钱',money - 100)"><span>花钱</span></button></div></template><script>export default{props:{"money"}}</script>
解释一下过程:App.vue中有个:money=”total”,将这个money给了Child.vue,Child.vue能看到这个money,Child.vue想花钱,就会触发一个事件”我要花钱”,将money-100传给监听Child.vue的父组件App.vue,App.vue发现Child.vue有这个”我要花钱”事件,便通过$event拿到传过来的money-100的结果,然后渲染更新。
现在我们用.sync来简写App.vue里的那句:
<Child :money="total" v-on:我要花钱="total = $event" />
简写为:
<Child :money.sync="total" />
完!
