平時工作中使用vue比較多,那么組件之間通信的方式有好幾種,在此總結一下。
1,父子組件之間
1.1,子傳父,通過$emit發送事件,然后父組件通過$on來接收事件
1.2,其實還有一種情況,父傳子也可以通過$emit來傳遞,不過呢這個有一點點特殊,可以參考如下代碼,下面就是父組件向子組件傳遞事件的情況,這個還需要制定組件名稱
<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, 非父子之間的傳遞
2.1 一般簡單的就用eventBus了,還是貼一下大概的寫法吧
//申明一個獨立的空vue實例,一般就寫在mian.js中
//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了
2.3 當然,如果不想使用vuex,可以使用簡化版的vuex,vue.observe(),代碼示例如下:這個和vuex的使用非常像
//在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);
基本就這么多吧,之前在網上看別人總結的貌似還有很多其他方法,但是自己主要就是使用上面的幾種