之前文档里对.sync的介绍没看懂。我真的有东西要考虑以下两个父子组件://parentcomponent{template:`
I'mparent
parentCount:{{parentCount}}
`,data(){return{parentCount:1}},}//子组件{template:`
I'mchild
childCount:{{childCount}}
`,props:['childCount'],}父组件将值parentCount作为propchildCount传递给子组件。我们希望点击子组件中的按钮,使得父组件中的parentCount和子组件中的childCount都+1,我们想当然地认为://Subcomponentmethods:{handleClickAdd(){//添加即可1到子组件中的childCount,作为数据源,parentCount也会+1this.childCount+=1}}尝试点击按钮,会发现父组件的数据没有变化:同时,控制台警告:vue.js:634[Vuewarn]:Avoidmutatingapropdirectlyasthevaluewillbeoverwrittenwhenevertheparentcomponentre-renders.相反,使用数据或计算道具erty基于道具的价值。Propbeingmutated:"childCount"foundin--->
这就是所谓的单向数据流父prop的更新会向下流向子组件,但是相反的方式想当然是行不通的。另一种思路:既然prop的流向是单向的,那么我们可以在子组件中抛出一个事件通知父组件更新parentCount,这样childCount自然会更新。别忘了,事件名称没有自动大小写转换,所以我们可以抛出一个叫update:childCount的事件——父组件,你传入的propchildCount被更新了!父组件监听事件后,只需将更新后的值赋给prop对应的数据源parentCount即可://子组件方法:{handleClickAdd(){this.$emit('update:childCount',this.childCount+1)}}//父组件``目前的代码满足我们的需求:我们回头看,父组件这样写有些繁琐——几乎要写两次childCount=parentCount。所以vue提供了.sync的缩写:在绑定prop的时候加上.sync,vue会自动为我们设置一个更新事件叫update:propName。因此,上面的父组件代码完全等价于:`
`有兴趣的也可以在源码中确认一下: