vue中 .sync的使用---子组件更新父组件数据
vue中 .sync的使用
vue 2.3.0+ 新增 的.sync修饰符
vue修饰符sync的功能是:当一个子组件改变了一个 prop 的值时,这个变化也会同步到父组件中所绑定。子组件更新父组件数据。
.sync的使用
sync不需要你去监听事件更新数据,
子组件中设置:
this.$emit("update:xx",xx), 子组件更新父组件数据
this.$emit("update:xx",xx), 前面带一个update:前缀,后面是props名称(传进来的props)
例如:
this.$emit("update:page",p)
父组件视图层中设置:
:page.sync="uPage"
例如:
要想实现 子组件 修改 父组件的属性的值
子组件 想要 修改 父组件 数据中心 title属性上的值-- '吴灿'
一、在.sync出现之前,要想实现子组件修改父组件的属性的值
<!-- 
要想实现 子组件 修改 父组件的属性的值 
子组件 想要 修改 父组件 数据中心 title属性上的值-- '吴灿'
-->
<div id="app">
<parent :ptitle="title" @test1="title = $event"></parent>
<p>子组件的数据--修改 父组件中的数据------> {{title}}</p>
</div>
<template id="parent">
<div>
<p>我是子组件parent</p>
<p>
<button @click="mod">点击 去修改--</button>
</p>
</div>
</template>
<script src="js/vue.js"></script>
<script>
// 子实例(子组件)
let Parent = {
props:['ptitle'],
data:function(){
return {
title2:'谷永康'
}
},
template:'#parent',
// 生命周期
mounted:function(){
console.log(this.ptitle);
},
methods:{
mod:function(){
this.$emit('test1',this.title2);
}
}
}
// 根实例(根组件)
let vm  = new Vue({
el:'#app',
data:function(){
return {
title:'吴灿'
}
},
// 生命周期
mounted:function(){
console.log(this.title);
},
components:{
Parent
}
})
</script>预览效果,如下所示:

点击按钮,修改

二、而.sync出现后,简化了代码
<!-- 
        要想实现 子组件 修改 父组件的属性的值 
        子组件 想要 修改 父组件 数据中心 title属性上的值-- '吴灿'
        步骤:
        (1)  this.$emit('update:title',this.title2);  在子组件中 指明修改 父组件上的某个属性
        (2)  在父组件的 视图层 <parent :title.sync="title"></parent>
        :title.sync ----子组件中 指明的属性
        title-----------父组件数据中心的属性
    -->
<div id="app">
<parent :ptitle="title" :title.sync="title"></parent>
<p>子组件的数据--修改 父组件中的数据------> {{title}}</p>
</div>
<template id="parent">
<div>
<p>我是子组件parent</p>
<p>
<button @click="mod">点击 去修改--</button>
</p>
</div>
</template>
<script src="js/vue.js"></script>
<script>
// 子实例(子组件)
let Parent = {
props:['ptitle'],
data:function(){
return {
title2:'谷永康'
}
},
template:'#parent',
// 生命周期
mounted:function(){
console.log(this.ptitle);
},
methods:{
mod:function(){
// 1. this.$emit('update:xxx',this.title2); ---'update:xxx' 指明修改 父组件上的某个属性
this.$emit('update:title',this.title2);
}
}
}
// 根实例(根组件)
let vm  = new Vue({
el:'#app',
data:function(){
return {
title:'吴灿'
}
},
// 生命周期
mounted:function(){
console.log(this.title);
},
components:{
Parent
}
})
</script>预览效果,如下图所示:

点击按钮修改

 吐槽一下
		   		
 
          
还没有留言,还不快点抢沙发?