eventBus
先在main.js中指定eventBus:Vue.prototype.$EventBus = new Vue()
相当于挂载一个Vue的实例。
下面开始尝试使用:
先编写comA用于触发一个事件在父组件中响应减操作并接受B组件的传过来的数据最后console.log出来:
comA
<template>
<button @click="increment()">+ 加并接受另一个组件的值!</button>
</template>
<script>
export default {
name: 'IncrementCount',
data() {
return {
num: 1,
deg: 1
};
},
methods: {
increment() {
this.$EventBus.$emit("incremented",{
num: this.num,
deg: this.deg
});
}
},
mounted() {
// 这是响应change事件
this.$EventBus.$on("change", test => {
console.log(test)
})
}
}
</script>
然后我们编写comB,用于触发一个事件在父组件中响应加操作并传递值到comA:
comB
<template>
<button @click="decrease()"> -减 </button>
</template>
<script>
export default {
name: 'DecreaseCount',
data() {
return {
num: 1,
deg: 1,
show_data: 1000
}
},
methods: {
decrease() {
this.$EventBus.$emit("decreased", {
num: this.num,
deg: this.deg,
show_data: this.show_data // show_data就是要传递到组件A的值
})
}
}
}
</script>
comC(A和B的parent)
<template>
<div id="root">
<IncrementCount />
<DecreaseCount />
<div>{{ degValue }}</div>
<div>{{ fontCount }}</div>
<div>{{ backCount }}</div>
</div>
</template>
<script>
import IncrementCount from '../components/add_event_bus';
import DecreaseCount from '../components/decrease_event_bus';
export default {
name: 'App',
components: {
IncrementCount,
DecreaseCount
},
data() {
return {
degValue: 0,
fontCount: 0,
backCount: 0
};
},
mounted() {
// 接收A组件的incremented事件
this.$EventBus.$on("incremented", ({num, deg}) => {
this.fontCount += num
this.$nextTick(() => {
this.backCount += num
this.degValue += deg
})
})
// 接收B组件的decreased事件
this.$EventBus.$on("decreased", ({num, deg}) => {
this.fontCount -= num
this.$nextTick(() => {
this.backCount -= num
this.degValue -= deg
// 这里触发change事件
this.$EventBus.$emit("change", 1000)
})
})
}
}
</script>