Vue組件間通訊

一邊學習前端,一邊經過博客的形式本身總結一些東西,固然也但願幫助一些和我同樣開始學前端的小夥伴。html

若是出現錯誤,請在評論中指出,我也好本身糾正本身的錯誤前端

author: thomaszhouvue

vue組件間通訊

  • 父子組件之間-數據通訊
  • 父子組件之間-方法通訊
  • 兄弟組件之間-通訊

寫Vue項目的過程當中,組件之間的通訊很是頻繁,像父子通訊的props和$emit方法是不少人都知道的,固然我這裏確定也要提一提嘛~可是兄弟間的通訊方法大部分都是提倡構建evenBusbash

父子組件之間-數據通訊

父組件向子組件傳遞(props)

  • 父組件引用子組件的時候利用v-bind去綁定mseeage,傳遞給子組件(對應就是msg)
  • 子組件要建立props選項,註冊傳遞的msg值,就能夠直接使用msg這個值了

父組件app

<template>
    <child :msg="message"></child>
</template>

<script>
import child from './child.vue';
export default {
    components: {
        child
    },
    data () {
        return {
            message: 'father message';
        }
    }
}
</script>
複製代碼

子組件vue函數

<template>
    <div>{{msg}}</div>
</template>

<script>
export default {
    props: {
        msg: {
            type: String,
            required: true
        }
    }
}
</script>
複製代碼

父組件直接獲取子組件的數據(this.$refs.ref的名字.變量

// 假設咱們要獲取子組件<son></son>的數據target
// 第一:子組件son要設置ref
<son ref="sonComponent"></son>
// 第二:用下面的語句去獲取,修改子組件的值
console.log(this.$refs.sonComponent.target); // 取值
this.$refs.sonComponent.target = '1'; // 修改值
複製代碼

子組件向父組件傳遞數據(emit)+ 子組件調用父組件方法

子組件經過 $emit 觸發父組件的方法(經過@add-parent-total="addTotal將 add-parent-total 和 addTotal聯繫起來)學習

  • 子組件經過$emit觸發add-parent-total事件
  • 父組件在引入組件時設置,@add-parent-total="addTotal",其中addTotal是父組件的方法
//html
<child @add-parent-total="addTotal"></child>
//根組件
var vm = new Vue({
    el: "#app",
    data:{
        total: 0
    },
    components: {
        Child
    },
    methods: {
//根組件中子組件改變根組件的方法
        addTotal(args){
            this.total++
            console.log(args);//args就是傳遞值帶的的參數
        }
    }
})
複製代碼
//定義子組件
var Child = {
//獲取data()中的數據,並添加一個點擊事件
    template: `<button @click="addCounter">{{counter}}</button>`,
    data(){
        return {
            counter: 0
        }
    },
    methods:{
        addCounter(){
            this.counter++;
            //自定義事件$emit傳回根組件,同時調用根組件方法
            this.$emit('add-parent-total',args)
        }
    }
}
複製代碼

父子組件之間-方法通訊

  • 父組件 --> 子組件:

    • ==引用子組件 並起名ref="demo1"而後 經過 this.$refs.demo1.getUser(elem) 調用子組件中的getUser方法並傳參(elem)==
  • 子組件 --> 父組件:

    • 方法一:子組件直接用this.$parent.xxxx這樣直接調用父組件的方法。
    • 方法二: 引用子組件並用 v-on 來作個監測的函數來檢測;子組件經過this.$emit('方法名',傳遞的參數)來調用父組件的方法
  • 父組件代碼ui

// 調用子組件
<son-demo ref="demo1" @sonname="son1"></son-demo>  <!--一些要寫明的屬性-->
複製代碼
import sonDemo from '../components/sondemo.vue'
export default {
    data() {
      return {
        sondemoVal: 'test'
      };
    },
    mounted() {
      this.$refs.demo1.getUser(this.sondemoVal); // 父 --> 子的方法
    },
    methods: {
      son1(temp) {
        console.log(`這裏是父組件的方法son1:${temp}`);
	  }
    },
}
複製代碼
  • 子組件
<template>
    <div>{{msg}}</div>
</template>
複製代碼
export default {
    methods: {
      getUser(temp) {
        console.log('sondemo--->'+temp);
	  }
	},
	mounted() {
          // this.$parent.son1('son'); 子 --> 父的方法一:
         this.$emit('sonname','son'); // 子 --> 父的方法二:
         // 'son'是傳遞的參數
	}
}
複製代碼

兄弟組件之間-通訊(或者非兄弟,非父子組件)

  • 適用於兄弟組件的狀況 和 非父子,非兄弟組件的狀況this

    • 方法一(使用簡單的狀況):本身建立一個事件總線eventBus來做爲通訊的橋樑(也適用於非父子,非兄弟組件的狀況)
    • 方法二(程序比較複雜的狀況)那就用Vuex(也適用於非父子,非兄弟組件的狀況)
    • 方法三⚠️:若是僅僅是某一個頁面,或者不多的頁面有兄弟組件A,B(非兄弟組件不適用)通訊的問題,推薦:**將該部分邏輯寫在父組件內,經過this.emit()發送到父組件進行邏輯的編寫,而後經過this.refs.子組件name(要本身提早設置),來取到另外一個子組件的值,具體以下spa

    舉例: 子組件A 要修改 子組件B 的time值???
    
    <son1 refs="son1" @changeElem = "change"></son1>
    <son2 refs="son2"></son2>
    
    思路:
        子組件son1:click觸發一個$emit("changeElem", val);要將son2組件的time修改成val
        父組件: 經過@changeElem = "change"接收事件,編寫change方法
        change(elem) {
            this.$refs.son2.time = elem;
        }
    複製代碼

Vuex的用法看這裏

這裏主要講方法一

vue2中廢棄了dispatch和broadcast廣播和分發事件的方法。

因此在vue2.0中能夠經過實例一個vue實例Bus做爲媒介,要相互通訊的兄弟組件之中,都引入Bus,以後經過分別調用Bus事件觸發和監聽來實現組件之間的通訊和參數傳遞

  • 建立一個eventBus.js做爲橋樑(例子直接把js文件放在與組件同一個目錄下),內容以下:
import Vue from 'vue'
export default new Vue;
複製代碼
  • 建立兩個子組件,son1.vue 和 son2.vue
// son1.vue 發送值

<template>
	<div class="ex">
		<button @click="sendMsg">點擊我傳送值</button>
	</div>
</template>

<script>
  import Bus from './eventBus' // 引入eventBus文件
  export default {
    data () {
      return {
	  }
    },
	methods: {
      sendMsg() {
        Bus.$emit('msg', '我要傳給兄弟組件們,你收到沒有');//傳遞msg,第二個參數就是msg的值
	  }
	}
  }
</script>
複製代碼
// son2.vue 接受值

<template>
	<div class="ex">
		{{message}}
	</div>
</template>

<script>
  import Bus from './eventBus' // 引入eventBus文件
  export default {
    data () {
      return {
        message: '變化前'
	  }
    },
	mounted() {
        let self = this;
        // 利用$on來監聽msg值
        Bus.$on('msg', (e) => {
            self.message = e;
            console.log(`傳來的數據是:${e}`);
        });
	}
  }
</script>
複製代碼
相關文章
相關標籤/搜索