.sync 修饰符:进行父子组件间相互传递数据

2.3.0+ 新增

在有些情况下,我们可能需要对一个 prop 进行“双向绑定”。不幸的是,真正的双向绑定会带来维护上的问题,因为子组件可以修改父组件,且在父组件和子组件都没有明显的改动来源。

这也是为什么我们推荐以 update:myPropName 的模式触发事件取而代之。举个例子,在一个包含 title prop 的假设的组件中,我们可以用以下方法表达对其赋新值的意图:

this.$emit('update:title', newTitle)

然后父组件可以监听那个事件并根据需要更新一个本地的数据属性。例如:

<text-document

  v-bind:title="doc.title"

  v-on:update:title="doc.title = $event"

></text-document>

为了方便起见,我们为这种模式提供一个缩写,即 .sync 修饰符:

<text-document v-bind:title.sync="doc.title"></text-document>


示例:

在父组件index.vue下引入子组件childrenOne为例,使用.sync属性,会在mounted生命周期里面打印出childrenOne,而不是index。

<template>
    <div class="content">
            <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:'parents'
                },
            }
        },
        mounted (){
       //childrenOne
            console.log('test', this.doc.title);
        },
        components : {
            childrenOne
        }
    }
</script>
在子组件childrenOne.vue的生命周期mounted里面通过
this.$emit('update:title', this.newTitle);
设置title属值
<template>
    <div class="content">
        {{ title }}
    </div>
</template>
<script type="text/javascript">
    export default{
        props:{
            title: ''
        },
        data () {
            return {
                newTitle:'childrenOne'
            }
        },
        mounted (){
            this.$emit('update:title', this.newTitle);
        },
    }
</script>
原文地址:https://www.cnblogs.com/tanweiwei/p/10607413.html