平時工做中使用vue比較多,那麼組件之間通訊的方式有好幾種,在此總結一下。vue
1,父子組件之間vuex
1.1,子傳父,經過$emit發送事件,而後父組件經過$on來接收事件
1.2,其實還有一種狀況,父傳子也能夠經過$emit來傳遞,不過呢這個有一點點特殊,能夠參考以下代碼,下面就是父組件向子組件傳遞事件的狀況,這個還須要制定組件名稱app
<template> //這就是引入的一個組件 <pull ref="testPull"> <p @click="test">我來試試啦</p> </pull> </template> <script> methods:{ test(){ console.log('emit'); // this.$emit('pull'); //直接傳遞不行 this.$refs.testPull.$emit('pull'); 能夠指定組件,而後傳遞事件 // this.$Event.$emit('pull') //經過eventBus傳遞也是能夠的 } } </script>
2, 非父子之間的傳遞ui
2.1 通常簡單的就用eventBus了,仍是貼一下大概的寫法吧this
//申明一個獨立的空vue實例,通常就寫在mian.js中spa
//main.js: Vue.prototype.Event=new Vue()
// 子組件: show1(){ console.log(this.Event); this.Event.$emit('host',1) }
// 父組件:寫在mounted中 mounted(){ this.Event.$on('host', (msg)=>{ console.log('執行了'); console.log(msg); this.show1(); }) }
2.2 複雜一點的就用vuex了prototype
2.3 固然,若是不想使用vuex,可使用簡化版的vuex,vue.observe(),代碼示例以下:這個和vuex的使用很是像code
//在src文件夾根目錄想新建store.js
import Vue from 'vue'; export const store=Vue.observable({ host_id:'', //本身的uid current_family_data:null, applied_team_id:[], team_id:-1 });
export const mutations={ set_host_id(host_id){ store.host_id=host_id }, set_current_family(data){ store.current_family_data=data; }, set_applied_team(data){ store.applied_team_id=data; }, set_team_id(data){ store.team_id=data; } };
//其餘組件使用,先引入store.js
import {store,mutations} from '../store';
mutations.set_current_family(family);
基本就這麼多吧,以前在網上看別人總結的貌似還有不少其餘方法,可是本身主要就是使用上面的幾種blog