414 字
2 分钟
Vue-组件通信
前言
vue组件通信的方式如此之多 今天我们来总结一下 完整代码
一、 props、$emit/v-on
父组件通过props向子组件传递数据 子组件使用事件抛出一个值
父组件代码
<template> <div class="parent"> <h4>我是父组件</h4> <child :title="title" @getMsg="getMsgFromChild"></child> <div>子组件向我传递的消息 <b>{{ msgFromChild }}</b></div> </div></template>
<script>// @ is an alias to /srcimport child from '@/components/child.vue'
export default { data(){ return { title: '我是来自父组件的title', msgFromChild: '' } }, methods: { getMsgFromChild(msg){ this.msgFromChild = msg } }, components: { child }}</script>子组件代码
<template> <div class="child"> <h4>我是子组件</h4> <div>这是来自父组件的title: <b>{{ title }}</b></div> <button @click="sendMsgToParent">点我向父组件传递信息</button> </div></template><script> export default { props: ['title'], methods: { sendMsgToParent(){ this.$emit('getMsg','我是来自子组件的信息') } } }</script>二、 事件总线 $on/$emit
通过事件总线的话我们需要在Vue原型上添加一个Vue实例作为事件总线, 实现组件间相互通信,从而不受组件关系影响
// 在main.js中Vue.prototype.$bus = new Vue()
// 子组件中通过 $bus.$emit发送事件this.$bus.$emit('getMsgByBus','我是通过事件总线传递的信息')
// 父组件通过 $bus.$on 来监听事件this.$bus.$on('getMsgByBus',(msg)=>{ this.msgFromChild = msg})在原型上添加一个vue实例其实就是需要用到实例的$emit和$on 方法 我们也可以自己写一个事件总线
class Bus { constructor(){ this.callbacks = {} } $on(name, fn){ this.callbacks[name] = this.callbacks[name] || [] this.callbacks[name].push(fn) } $emit(name, args){ if(this.callbacks[name]){ this.callbacks[name].forEach(cb => cb(args)) } }}那么现在就可以在原型上添加Bus的实例达到同样的效果
Vue.prototype.$bus = new Bus()