子组件与父组件怎么传递?.sync修饰符进行父子组件间相互传递数据
子组件与父组件怎么传递?.sync修饰符进行父子组件间相互传递数据this.$emit('update:title' this.newTitle);<template> <div class="vuexWrap common"> <childrenOne :title.sync="doc.title"></childrenOne> </div> </div> </template> <script type="text/javascript"> import childrenOne from '../../components/childrenOne.vue' export default{ data () { return { doc:{ title:'index' } } } mou
问题:.sync修饰符的作用?vue 2.3.0 新增
简要回答:
允许prop进行双向绑定,以this.$emit(update:PropName newValue)的模式触发事件。
即:
<text-document v-bind:title.sync="doc.title"></text-document>
相当于:
<text-document v-bind:title="doc.title" v-on:update:title="doc.title = $event" ></text-document>
示例:
以在index.vue下引入childrenOne子组件为例,使用.sync属性,会在mounted生命周期里面alert弹出childrenOne,而不是index。
<template> <div class="vuexWrap common"> <childrenOne :title.sync="doc.title"></childrenOne> </div> </div> </template> <script type="text/javascript"> import childrenOne from '../../components/childrenOne.vue' export default{ data () { return { doc:{ title:'index' } } } mounted (){ //childrenOne alert(this.doc.title); } components : { childrenOne } } </script>
在childrenOne.vue的生命周期mounted里面通过
this.$emit('update:title' this.newTitle);
设置title属值
<template> <div class="OneWrap common"> {{title}} </div> </template> <script type="text/javascript"> export default{ props:{ title:"" } data () { return { newTitle:"childrenOne" } } mounted (){ this.$emit('update:title' this.newTitle); } } </script>
编辑器:完整demo: