在VUE里父組件給子組件間使用props方式傳遞數據,但是希望父組件的一個狀態值改變然后子組件也能監聽到這個數據的改變來更新子組件的狀態。
場景:子組件通過props獲取父組件傳過來的數據,子組件存在操作傳過來的數據並且傳遞給父組件。
比如想實現一個switch開關按鈕的公用組件:
1.父組件可以向按鈕組件傳遞默認值。
2.子組件的操作可以改變父組件的數據。
3.父組件修改傳遞給子組件的值,子組件能動態監聽到改變。
比如父組件點擊重置,開關組件的狀態恢復為關閉狀態:
方法1:
1、因為存在子組件要更改父組件傳遞過來的數據,但是直接操作props里定義的數據vue會報錯,所以需要在data里重新定義屬性名並將props里的數據接收。
2、首先想到的肯定是在computed計算屬性里監聽數據的變化,那就直接在computed里監聽父組件傳遞過來的props數據的變化,如果有變動就進行操作,如:
export default { name: 'SwitchButton', props: { status: { type: Boolean, default () { return false } } }, data () { return { switchStatusData: this.status // 重新定義數據 } }, computed: { switchStatus: function () { return this.status // 直接監聽props里的status狀態 } } } }
這樣就可以在使用switchStatus的地方動態的監聽到父組件status的變化。似乎只針對簡單的數據類型有效。
方法2:
使用watch和computed組合實現:如
export default { name: 'SwitchButton', props: { status: { type: Boolean, default () { return false } } }, data () { return { switchStatusData: this.status } }, computed: { switchStatus: function () { return this.switchStatusData // 監聽switchStatusData 的變化 } }, watch: { status (newV, oldV) { // watch監聽props里status的變化,然后執行操作 console.log(newV, oldV) this.switchStatusData = newV } }, methods: { switchHandleClick () { this.switchStatusData = !this.switchStatusData this.$emit('switchHandleClick', this.switchStatusData) } } }
下面是實現該組件的代碼:
<template> <span class="switch-bar" :class="{'active': switchStatus}" @click="switchHandleClick"><span class="switch-btn"></span></span> </template> <script> export default { name: 'SwitchButton', props: { status: { type: Boolean, default () { return false } } }, computed: { switchStatus: function () { return this.status } }, // watch: { // status (newV, oldV) { // console.log(newV, oldV) // this.switchStatusData = newV // } // }, methods: { switchHandleClick () { const switchStatusData = !this.switchStatus this.$emit('switchHandleClick', switchStatusData) } } } </script> <style lang="stylus" scoped> @import "~styles/varibles.styl" .area-wrapper line-height: .8rem; padding: 0 .4rem; .switch float: right; font-size: 0; .switch-bar position: relative; display: inline-block; width: .8rem; height: .4rem; border-radius: .4rem; background: #ddd; border: 2px solid #ddd; vertical-align: middle; transition: background .3s, border .3s; &.active background: $bgColor; border: 2px solid $bgColor; .switch-btn left: .4rem; background: #fff; .switch-btn position: absolute; left: 0px; display: inline-block; width: .4rem; height: .4rem; border-radius: .2rem; background: #fff; transition: background .3s, left .3s; </style>