一,前言
vue 修饰符sync的功能是:当一个子组件改变了一个 prop 的值时,这个变化也会同步到父组件中所绑定
.sync 修饰符,只是作为一个编译时的语法糖存在。它会被扩展为一个自动更新父组件属性的 v-on 监听器。
// 你的代码
<comp :foo.sync="bar"></comp>
// 编辑后的代码
<comp :foo="bar" @update:foo="val => bar = val"></comp>
所以在子组件中,需要更新父组件的数据时,使用
this.$emit('update:XXX',XXX)
// update:是被固定的也就是vue为我们约定好的名称部分
二,案例
父组件源码
// 父组件源码
<template>
<div class="app-container">
<Test :parent-obj.sync="parentObj" />
</div>
</template>
<script>
export default {
components: {
Test: () => import('./components/Test')
},
data () {
return {
parentObj: {
value: 'init'
}
}
},
watch: {
parentObj: {
handler (obj) {
var val = obj.value
debugger
},
// immediate: true,
deep: true
}
}
}
</script>
子组件源码
// 子组件源码
<template>
<input v-model="childObj.value" type="text" class="input-cls">
</template>
<script>
export default {
props: {
parentObj: {
type: Object,
default () {
return {}
}
}
},
data () {
return {
childObj: {
value: ''
}
}
},
watch: {
childObj: {
handler (obj) {
var val = obj.value
debugger
// update:是被固定的也就是vue为我们约定好的名称部分
this.$emit('update:parentObj', obj)
},
// immediate: true,
deep: true
},
parentObj: {
handler (obj) {
var val = obj.value
// this.childObj = this.$common.deepCloneObj(obj)
this.childObj = obj
debugger
},
immediate: true,
deep: true
}
}
}
</script>
<style lang="scss" scoped>
.input-cls {
padding: 4px 8px;
border: 1px solid #ddd;
}
</style>