.sync修飾符的作用
Vue中的數據是單向數據流:父級 prop 的更新會向下流動到子組件中,但是反過來則不行,即子組件無法直接修改父組件中的數據。
但我們常常會遇到需要在子組件中修改父組件數據的場景。.sync修飾符就可以幫助我們實現這種功能。
不使用.sync修飾符的寫法
父組件代碼:
<biz-system-detail
:is-show="detailVisible"
@update:isShow="func"></biz-system-detail>
methods中的方法:
func (val) {
this.detailVisible = val
}
子組件中的方法:
onClose () {
this.$emit('update:isShow', false)
}
注意:this.$emit()中update后的字段要與父組件中保持一致
使用.sync修飾符的寫法
父組件
<biz-system-detail
:is-show.sync="detailVisible"></biz-system-detail>
子組件中
onClose () {
this.$emit('update:isShow', false)
// 或者如下也可以
this.$emit('update:is-show', false)
}
即:使用sync修飾符與 $emit(update:xxx)時 ,駝峰法 和 - 寫法都可以,而且也不需要與父組件保持一致。