组建通信的基本模式:父子组件的关系可以总结为 prop 向下传递,事件向上传递。父组件通过 prop 给子组件下发数据,子组件通过事件给父组件发送消息
组件通信的常用三种方式
1.props(父组件向子组件传值)parent.vue
<template> <p> <parent-child :childname="childname"></parent-child> </p></template><script> import child from "./child" export default { components: { "parent-child" : child },data(){ return { childname : "我是child哦" } } }</script>
child.vue
<template> <p id="child"> child的名字叫:{{childname}}<br> </p></template><script> export default { props:{ childname :{ type:string, default: "" } } }</script>
2.$emit(子组件向父组件传值–局部消息订阅)parent.vue
<template> <p> <parent-child :childname="childname" @childnotify="childreceive"></parent-child> </p></template><script> import child from "./child" export default { components: { "parent-child" : child },data(){ return { childname : "我是child哦" } },methods:{ childreceive(params){ this.$message(params) } } }</script>
child.vue
<template> <p id="child"> child的名字叫:{{childname}}<br> </p></template><script> export default { props:{ childname :{ type:string, default: "" } },methods:{ childnotify(params){ this.$emit("childnotify","child的名字叫"+this.childname); } } }</script>
3.bus全局消息订阅bus.js
const install = (vue) => { const bus = new vue({ methods: { on (event, ...args) { this.$on(event, ...args); }, emit (event, callback) { this.$emit(event, callback); }, off (event, callback) { this.$off(event, callback); } } }) vue.prototype.$bus = bus;}export default install;
main.js
import bus from "./assets/js/bus";vue.use(bus);
child.vue
<template> <p id="child"> child的名字叫:{{childname}}<br> <el-button type="primary" @click="brothernotity">向child2打招呼</el-button> </p></template><script> export default { props:{ childname :{ type:string, default: "" } },methods:{ childnotify(params){ this.$emit("childnotify","child的名字叫"+this.childname); }, brothernotity(){ this.$bus.$emit("child2","child2你好呀"); } } }</script>
child2.vue
<template> <p id="child2"> child2的名字叫:{{child2name}} </p></template><script> export default { props:{ child2name :{ type:string, default: "" } }, created(){ this.$bus.$on("child2",function(params){ this.$message(params) }) }, beforedestroy() { this.$bus.$off("child2",function(){ this.$message("child2-bus销毁") }) } }</script>
推荐学习:vue.js教程
以上就是vue常用的组件通信方式的详细内容。
