vue中我們會遇到很多父子組件通信的需求,
下面簡單列一下,父子組件通信的幾種情況
1:父組件向子組件傳值:使用prop向子組件傳值;
2:子組件實時監聽父組件傳來的值的變化:使用watch去監聽父組件傳來的值;
3:父組件可以通過this.$refs.name.去訪問子組件的值或方法;
4:子組件可以通過this.$parent.去訪問父組件的值或方法;
總結了一下,感覺好像挺全面的,好像不缺啥了。。。。
但是仔細一想,父組件如何去監聽子組件的值呢?如何根據子組件中的某個值的變化,父組件作出響應呢????
研究了一下,需要借用vueX!!!!超級大無敵的vueX
上個例子:
先看子組件
<template> <div><el-button @click="dd()">自定義組件內的按鈕</el-button> </div> </template> <script> import { mapGetters,mapActions } from 'vuex'; export default { watch:{ text:{ handler(newVal){ this.$store.dispatch('user/setText',newVal); }, immediate:true, } }, data(){ return { text:"自定義組件", } }, props:['propObj'],//外部傳值 methods:{ ...mapActions([ 'setText' ]), dd(){ if(this.propObj.name==2){ this.propObj.name="哈哈"; this.text="自定義組件"; this.$emit('update:propObj', this.propObj) }else{ this.propObj.name=2; this.text="????????????????"; this.$emit('update:propObj', this.propObj) } } } } </script>
子組件中,點擊按鈕,會改變text的值,
我們用watch去監聽,text值的變化,它如果變化了,就調用vueX中的actions方法,就是把vuex中的一個變量設置成text的值。
再來看看父組件中,只看computed即可:
<script> import { mapGetters } from 'vuex'; import Lala from '@/components/lala.vue'; export default { computed: { ...mapGetters(['childText' ]) }, } </script>
父組件中,將vueX中的一個getter值作為計算屬性,這不是就完美的監聽了子組件值的變化了嘛!!!有了以上的幾種方法,感覺可以在組件之間任意穿梭了