.sync修饰符相当于编译时的一个语法糖,它会被扩展为一个自动更新父组件的v-on监听器。
场景:父组件给子组件数据,子组件要修改数据不能直接修改,要通过父组件修改数据再给到子组件的方式修改。
Vue规则:
组件不能修改prop外部数据;
$emit可以触发事件并传参;
$event可以获取$emit的参数
由于以上场景比较常见,尤雨溪发明了.sync修饰符
示例代码:
<comp :foo.sync="bar"></comp>
相当于:
<comp :foo="bar" @update:foo="val => bar=val"></comp>
<comp v-bind:foo="bar" v-on:update:foo="val => bar=val"></comp>
当子组件需要更新foo的值时,它需要显性触发一个更新事件:
this.$emit('update:foo', newValue)
Vue的修饰符.sync的功能是:当一个子组件改变了一个prop的值时,这个变化也会同步到父组件所绑定
// 如何调用 方式1=方式2=方式3
//方式1
<abc :province.sync="a" :city.sync="b" :area.sync="c"/>
//方式2
<abc :province="a" @update:province="v=>a=v" :city="b" @update:city="v=>b=v" :area="c" @update:area="v=>c=v"/>
//方式3
<abc :province="a" v-on:update:province="v=>a=v" :city="b" v-on:update:city="v=>b=v" :area="c" v-on:update:area="v=>c=v"/>
// 以下为组件
<template>
<div>
<input v-model="thisPageProvince"/>
<input v-model="thisPageCity"/>
<input v-model="thisPageArea"/>
</div>
</template>
<script>
export default {
name: 'Abc',
props: {
province: {
type: null,
default: ""
},
city: {
type: null,
default: ""
},
area: {
type: null,
default: ""
},
},
computed:{
thisPageProvince:{
get(){
return this.province
},
set(v){
this.$emit('update:province', v)
}
},
thisPageCity:{
get(){
return this.city
},
set(v){
this.$emit('update:city', v)
}
},
thisPageArea:{
get(){
return this.area
},
set(v){
this.$emit('update:area', v)
}
},
},
data() {
return {}
},
mounted() {
},
methods: {}
}
</script>
<style lang="scss" scoped>
</style>
// 联想下v-model 本人感觉还是 .sync好
<input v-model="test">
本质上是
<input :value="test" @input="test=$event.target.value">
本质上也是
<input v-bind:value="test" v-on:input="test=$event.target.value">
网友评论