<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>兄弟组件通信</title>
</head>
<body>
<div id="app">
<brother></brother>
<hr>
<sbrother></sbrother>
</div>
<template id="brother">
<div>
哥哥
{{msg}}
<button @click="gchan">哥哥</button>
</div>
</template>
<template id="sbrother">
<div>
弟弟
{{msg}}
{{change()}}
</div>
</template>
<script src="vue.js"></script>
<script>
let bus=new Vue();
Vue.component("brother",{
template:"#brother",
data(){
return {
msg:"我是你哥哥"
}
},
methods:{
gchan(){
bus.$emit("suibian",this.msg)
}
}
});
Vue.component("sbrother",{
template:"#sbrother",
data(){
return {
msg:"我是你弟弟"
}
},
created(){
},
mounted(){
bus.$on("suibian",(val)=>{
this.msg=val;
})
},
methods:{
change(){
}
}
})
new Vue({
}).$mount("#app")
</script>
</body>
</html>
VUE 兄弟通信(除了父子就是兄弟)
最新推荐文章于 2024-07-02 17:50:31 发布
本文通过一个具体的示例,展示了如何在Vue中实现兄弟组件之间的通信。通过使用全局事件总线,哥哥组件可以向弟弟组件发送消息,弟弟组件能够接收到这些消息并更新其状态,实现了跨组件的数据传递。
409

被折叠的 条评论
为什么被折叠?



