2019-07-15 vue非父子组件之间的通信
描述:vue中组件之间的通信有很多种,目前常用的有vuex状态管理模式、event-bus(事件总线);本篇文章讲详细介绍如何在vue项目中使用event-bus来监听、触发、和撤销事件(on,emit,off)
父子组件之间的通信
如下:有两个组件,父组件和子组件,父组件向子组件传递数据通过props,子组件向父组件发送数据通过$emit和@click两个方法
// 父组件father.vue
<template>
<div class="father">
<h2>我是父组件</h2>
</div>
</template>
// 子组件child.vue
<template>
<div class="son">
<h3>我是子组件</h3>
</div>
</template>
父组件向子组件通信-props
- 在父组件中注册子组件,并传值
<template>
<div class="father">
<h2>我是父组件</h2>
<child message="我是父组件"></child> // 向子组件传值
</div>
</template>
<script>
import child from './child';
export default {
components: {
child
}
}
</script>
- 在子组件中定义props属性接受父组件传过来的值
<template>
<div class="son">
<h2>我是子组件</h2>
<p>父组件传过来的值:{{ message }}<p>
</div>
</template>
<script>
export default {
props: ['message'] // 名字要跟父组件中的属性名字对应,可以多个
}
</script>
父组件调用子组件的事件-$ref获取子组件的实例
- 在父组件中给子组件添加
$ref
属性可以获取到子组件的实例对象
父组件:
<template>
<div class="father">
<h2>我是父组件</h2>
<child ref="child" message="我是父组件"></child> // 向子组件传值
</div>
</template>
<script>
import child from './child';
export default {
components: {
child
}
}
</script>
子组件:
<template>
<div class="son">
<h2>我是子组件</h2>
<p>要传给父组件的值:{{ message }}</p>
<button value="传值" @click="send"></button>
</div>
</template>
<script>
export default {
data() {
data: {
message: '这是子组件的值,传给父组件'
},
methods: {
send() { // 触发$emit事件
this.$emit('receive', this.message); // 父组件中的@事件名属性
}
}
}
}
</script>
- 在父组件中使用
this.$ref.child.send()
调用子组件实例的事件方法
子组件向父组件通信-$emit,@事件名
- 子组件中定义传送数据触发事件
<template>
<div class="son">
<h2>我是子组件</h2>
<p>要传给父组件的值:{{ message }}</p>
<button value="传值" @click="send"></button>
</div>
</template>
<script>
export default {
data() {
data: {
message: '这是子组件的值,传给父组件'
},
methods: {
send() { // 触发$emit事件
this.$emit('receive', this.message); // 父组件中的@事件名属性
}
}
}
}
</script>
- 父组件中定义方法名接受子组件传过来的信息
<template>
<div class="father">
<h2>我是父组件</h2>
<p>子组件传过来的值:{{ father_message }}</p>
<child @receive="receive"></child>
</div>
</template>
<script>
import child from './child';
export default {
components: {
child
},
data() {
father_message: '子组件传过来之前的数据'
},
methods: {
receive(msg) {
this.father_message = msg;
}
}
}
</script>
非父子组件之间的通信
首先,建立一个单独的bus文件,保存在组件之外
如:在vue项目目录下的components目录同级下新建一个Bus文件夹,里面新建文件bus.js
// bus.js文件
import Vue from 'vue'
// 使用 Event Bus
const bus = new Vue()
export default bus
然后,在需要传数据的组件里定义#emit事件
import Bus from 'bus的路径' // 引入bus文件
// 在需要的触发的函数里写入$emit方法
Bus.$emit('监听方法名', 参数);
最后,在需要监听事件的组件里created()里定义监听函数
import Bus from 'bus的路径' // 引入bus文件
// 在created()钩子函数里写入监听事件
created() {
let that = this;
Bus.$on('监听方法名', res => {
// 定义回调函数,res为接受的参数
// 如果使用this,最好使用that代替
});
}
// 在组件销毁前清除事件监听
beforeDestroy() {
Bus.$off('监听方法名');
}
至此,组件之间通信方式之一的公交车方法event-bus介绍完毕,希望能帮助到大家!