解决A组件与B组件间非父子,子父关系,跨组件的传参与函数调用
1、lib文件下新建storr.js
const Mutual = {
// 事件队列
Queue: {},
//接收
// 将接收到的函数放进队列中,但是函数是不触发的
on(key, fn) {
//防止重复添加事件队列
if (!this.Queue[key]) {
this.Queue[key] = [];
}
this.Queue[key].push(fn);
},
//发送
emit(key, param) {
//取出待触发队列
let Grasp = this.Queue[key];
if (Grasp) {
Grasp.forEach(fn => {
fn(param);
});
}
},
//销毁
delete(key) {
delete this.Queue[key];
}
}
export default Mutual;
使用如:A向B传参
A组件:
import store from '../lib/store.js';
//传参
store.emit("onDaily", "你的参数")
B组件:
import store from '../lib/store.js';
//接收
componentDidMount(){
store.on("onDaily", (data) => {console.log(data)})//data既A传的参数
store.on("onDaily", (data) => {this.onFun(data)})//调用函数
}
onFun(data){
console.log("这是一个方法")
}
//组件销毁同时销毁事件队列(根据不同情况需不需要销毁)
componentWillUpdate(){
store.delete("onDaily")
}
相对于Redux、父子层层传参的方式比较笨重繁琐,使用发布订阅快乐敲代码。