.sync

使用update更新父组件的数据

//父组件
<template>
    <div>
        父组件:{{title}}
        <childDom :title="title" @update:title="title=$event"></childDom>
    </div>
</template>

<script>
import childDom from '../components/Father3-Child'
export default {
    data(){
        return {
            title:'简单我的简单'
        }
    },
    components:{childDom}
}
</script>
//子组件
<template>
    <div>
        <div>子组件:{{title}}</div>
        <button @click="$emit('update:title','哈哈哈')">点我更新父组件的数据</button>
    </div>
</template>

<script>
export default {
    props:['title'],
}
</script>
点击前

点击后

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

//父组件
<template>
    <div>
        父组件:{{title}}
        <childDom :title.sync="title"></childDom>
    </div>
</template>

<script>
import childDom from '../components/Father3-Child'
export default {
    data(){
        return {
            title:'简单我的简单'
        }
    },
    components:{childDom}
}
</script>
//子组件
<template>
    <div>
        <div>子组件:{{title}}</div>
        <button @click="$emit('update:title','哈哈哈')">点我更新父组件的数据</button>
    </div>
</template>

<script>
export default {
    props:['title'],
}
</script>

注意带有 .sync 修饰符的 v-bind 不能和表达式一起使用 (例如 v-bind:title.sync=”doc.title + ‘!’” 是无效的)。取而代之的是,你只能提供你想要绑定的属性名,类似 v-model。

.sync常用于关闭弹框

//父组件
<template>
    <div>
        弹框是否显示:{{showDialog}}
        <childDom :showDialog.sync="showDialog" v-if="showDialog"></childDom>
        <button @click="showDialog=true">显示弹框</button>
    </div>
</template>

<script>
import childDom from '../components/Father3-Child'
export default {
    data(){
        return {
            showDialog:false,
        }
    },
    components:{childDom}
}
</script>
//子组件
<template>
    <div>
        <div class="dialog">
            <div class="content">
                <div>我是弹框</div>
                <button @click="$emit('update:showDialog',false)">点我关闭弹框</button>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    props:['showDialog'],
}
</script>

<style scoped>
.dialog{position:fixed;left:0;top:0;width:100%;height:100%;background:rgba(0,0,0,0.5);}
.content{width:200px;height:200px;position: absolute;left:50%;top:50%;transform:translate(-50%,-50%);background:#fff;}
</style>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容