vue 跨层级通信 (elment-ui的跨层级通信)
$emit和on
对于ChildA包裹ChildB的组件通信,可以采用elment-ui封装的通信,原理是通过递归去找到符合条件的$parent和$children,然后通信。
这种方法对于封装组件比较友好,也好管理通信,如果使用event-bus,多人合作可能比较难管理
emitter.js
function broadcast(componentName, eventName, params) {
this.$children.forEach((child) => {
var name = child.$options.componentName;
if (name === componentName) {
child.$emit.apply(child, [eventName].concat(params));
} else {
broadcast.apply(child, [componentName, eventName].concat([params]));
}
});
}
export default {
methods: {
dispatch(componentName, eventName, params) {
var parent = this.$parent || this.$root;
var name = parent.$options.componentName;
while (parent && (!name || name !== componentName)) {
parent = parent.$parent;
if (parent) {
name = parent.$options.componentName;
}
}
if (parent) {
parent.$emit.call(parent, eventName, params);
}
},
broadcast(componentName, eventName, params) {
broadcast.call(this, componentName, eventName, params);
}
}
};
父组件
<template>
<div>
<div>A组件</div>
<h3>{{ mes }}</h3>
<hr />
<slot></slot>
</div>
</template>
<script>
import emitter from "./emitter";
export default {
name: "childA",
componentName: "childA",
mixins: [emitter],
data() {
return {
mes: "",
};
},
mounted() {
this.$on("change", (msg) => {
this.mes = msg;
});
this.broadcast("childB", "getmesg", "我是childA的内容");
},
};
</script>
childB组件
<template>
<div>
b组件
<h3>{{ mes }}</h3>
<button @click="change">changeA</button>
</div>
</template>
<script>
import emitter from "./emitter";
export default {
name: "childB",
componentName: "childB",
mixins: [emitter],
data() {
return {
mes: "",
};
},
mounted() {
this.$on("getmesg", (msg) => {
this.mes = msg;
});
},
methods: {
change() {
this.dispatch("childA", "change", "我是b组件的内容");
},
},
};
</script>
代码地址:代码地址
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· .NET 进程 stackoverflow异常后,还可以接收 TCP 连接请求吗?
· SQL Server统计信息更新会被阻塞或引起会话阻塞吗?
· 本地部署 DeepSeek:小白也能轻松搞定!
· 传国玉玺易主,ai.com竟然跳转到国产AI
· 自己如何在本地电脑从零搭建DeepSeek!手把手教学,快来看看! (建议收藏)
· 我们是如何解决abp身上的几个痛点
· 如何基于DeepSeek开展AI项目
2017-03-29 webstrom 里面使用github
2017-03-29 webstrom 使用git