Vue 全局引入bus實現兄弟組件通信

1.簡述

本文是一篇記錄vue使用技巧的簡短文章,該文記錄的是vue中兄弟組件間通信的方式,之前經歷了第一個vue app項目,也是想積澱一下,之前是在項目中是在需要的vue中對bus進行引入,對於這類常見的工具最好提倡是全局引入進行一定的封裝。

2.局部使用案例

bus.js

import Vue from 'vue'
export const Bus = new  Vue();

接收總線通知

import {Bus,NotifyRefresh} from "../../common/js/Bus";
mounted() {
	console.log('PageOne mounted')
	Bus.$on(NotifyRefresh,(msg) =>{
       this.info = msg;
    });
},

發送總線通知

Bus.$emit(NotifyRefresh,'回傳消息');

3.全局bus的引入與使用技巧

/**
 * 描述:事件總線幫助工具
 * @ClassName eventBus
 * @Author apple
 * @Date 2019-04-20 19:58
 * @Version 1.0
 */

const EventBus = (Vue) => {
	Vue.prototype.$bus = new Vue({
		methods: {
			on(event, ...args) {
				this.$on(event, ...args);
			},
			emit(event, callback) {
				this.$emit(event, callback);
			},
			off(event, callback) {
				this.$off(event, callback);
			}
		}
	});
};
export default EventBus;

main.js 引入

import eventBus from './common/./common/helper/eventBus'
Vue.use(eventBus);

任何vue中不需要再進行引入,直接使用即可
發佈通知

this.$bus.on(NotifyRefresh,(msg) => {
  this.info = msg;
});

** 進行訂閱**

this.$bus.emit(NotifyRefresh,'bus回傳消息');

4.父子組件傳值方式

既然談到兄弟之間傳值,那麼也是來記錄下父子組件傳值吧。

  1. 子組件使用props 得以讓父組件向子組件傳值
 //子組件定義回調方法 以及參數
 this.$emit('funA','params');
 
 //父組件定義接收方法 並接收傳遞的參數
 <child @funA="methods"></child>
 methods(params){
  
 }
  1. 使用 parentparent 以及child進行傳值

子組件調用父組件方法進行傳值

父組件

setFatherInfo(info){
    this.childInfo = info;
}

子組件

notifyFather(){
    this.$parent.setFatherInfo('我是兒子我傳值');
}

父組件通知子組件改變值

父組件

<inner-child ref="innerChild"></inner-child>

methods:{
	changeChild(){
	  this.$refs.innerChild.$emit('changeInChild','88888');
	}
},

子組件

mounted() {
  this.$on('changeInChild',(msg) => {
      this.$refs.footer.innerHTML = msg;
  });
}

好的我所知道的也就這些方式

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章