Vue事件总线 evenbus 兄弟组件之间传值
vue传值方式主要有四种
- 1.路由带参数传值
- 2.父子组件之间传值,父传子用props,子传父用emit
- 3.如果是大项目可以使用vuex传值,小项目少页面可以使用evenbus之间进行传值
事件总线之间传值可以分为两种,一种全局事件传值,一种单独设一个js文件进行引用传值
第一种:全局使用,在main.js中用vue的原型对象上添加一个bus方法
Vue.prototype.bus = new Vue()
接着在第一个传值的组件内自定义一个传值方法
<template>
<div id="firstchild">
<h2>firstChild组件</h2>
<button @click="sendMsg">向组件传值</button>
</div>
</template>
<script>
export default {
name: "FirstChild",
methods: {
sendMsg() {
this.bus.$emit('userDefinedEvent','this message is from firstChild')
}
}
}
</script>
<style scoped>
</style>