父子組件嵌套時候 vue支持的是單向數據流,並不是雙向數據綁定的,
也就是常見的父組件通過props 傳遞數據進去,子組件通過emit派發事件,但是子組件是不能修改props的,因為這個數據是父組件的,
但是有的情況需要雙向綁定,例如 popup彈層,外側通過 某操作觸發彈層顯示傳遞props進去,
popup組件內部會點擊mask層 來取消顯示,
代碼說明
組件調用方式
<simpleCashier :cashier-visible.sync="cashierVisible"/>
內部組件改變屬性方式
props: {
cashierVisible: {
type: Boolean,
default: false
}
},
data() {
return {
}
},
computed: {
show: {
get() {
return this.cashierVisible
},
set(val) {
this.$emit('update:cashierVisible', val)
console.log(val)
}
}
},
需要注意的點有
1 外部傳遞進來的 cashierVisible ,內部props接受的cashierVisible 后, 不可直接使用,因為當點擊mask層組件會修改這個屬性,就違背了vue的單向數據流原則,會報錯
[Vue warn]: Avoid mutating a prop directly since the value will be
overwritten whenever the parent component re-renders. Instead,
use a data or computed property based on the prop's value. Prop being mutated: "cashierVisible"
2 按照上面說的我們把外部傳遞進來的cashierVisible 屬性換成計算屬性 show,需要寫set,get 如下
computed: {
show: {
get() {
return this.cashierVisible
},
set(val) {
this.$emit('update:cashierVisible', val)
console.log(val)
}
}
},
否則會報錯
[Vue warn]: Computed property "show" was assigned to but it has no setter.
在set里通過 this.$emit('update:cashierVisible', val) 把屬性改變傳遞出去,完成~ 不能再set里直接給show賦值,否則會報第一條錯誤