父子組件嵌套時候 vue支持的是單向數據流,並非雙向數據綁定的,
也就是常見的父組件經過props 傳遞數據進去,子組件經過emit派發事件,可是子組件是不能修改props的,由於這個數據是父組件的,vue
可是有的狀況須要雙向綁定,例如 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的單向數據流原則,會報錯this
[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) } } },
不然會報錯code
[Vue warn]: Computed property "show" was assigned to but it has no setter.
在set裏經過 this.$emit('update:cashierVisible', val) 把屬性改變傳遞出去,完成~ 不能再set裏直接給show賦值,不然會報第一條錯誤component