Last time we talked about the value transfer of parent-child components , Let's talk about it this time Vue of use eventBus Realize the value transfer of sibling components . A sibling component usually has multiple child components under the parent component , Subcomponents pass values to each other
. I wrote one here Todo List example , stay menu Below todoList After the component clicks the completion item, it is passed to finishList assembly .
<>1. establish eventBus.js
eventBus As a central event bus , For monitoring todoList Events thrown , And set out finishList Receive events for .
import Vue from 'vue' export default new Vue()
<>2. Reference in sibling component eventBus, And join in $emit and on method
TodoList: stay methods of use $emit Send delivery value .
// This is todoList assembly <script> import eventBus from '@/eventBus' export default {
name: "TodoList", data () { return { todoList: [] } }, methods : { // Pass the completion event to the completion list
handleFinish: function(index) { const eventFinished = this.todoList.splice(
index, 1)[0] eventBus.$emit('finishEvent', eventFinished) } }, } </script>
FinishList: stay created of use $on Receive delivery value .
// This is finishList assembly <script> import eventBus from '@/eventBus' export default {
name: "FinishList", data () { return { finishList: [] } }, created() {
// Add the passed completion event eventBus.$on('finishEvent', eventFinished => { this.finishList.push
(eventFinished) }) } } </script>
Technology
Daily Recommendation