Communication between brother components in Vue

When developing the Vue front-end, a component may consist of multiple sub-components, and they are written in different files. When one sub-component changes, how can the changed data be transferred to another component? I have learned a method, here is a record of learning.

Similar to the interface below, the whole main interface has two components on the left and right. When we click on the different options on the left, the interface on the right will display different interfaces.
Insert picture description here

main.js

Instantiate a new vue

export const eventBus = new Vue()

sideBar.vue

On the left sidebar interface, introduce the eventBus that was instantiated before, and bind the event

<template>
  <div class="sideBar">
    <el-col :span="20">
      <el-menu
          default-active="2"
          class="el-menu-vertical-demo"
          @open="handleOpen"
          @close="handleClose">
        <el-menu-item index="1" @click="messageContent('1')">
          <i class="el-icon-menu"></i>
          <span slot="title">博客管理</span>
        </el-menu-item>
        <el-menu-item index="2" @click="messageContent('2')">
          <i class="el-icon-menu"></i>
          <span slot="title">评论管理</span>
        </el-menu-item>
      </el-menu>
    </el-col>
  </div>
</template>


<script>
import {eventBus} from '@/main'

export default {
  name: "sideBar",
  methods: {
    messageContent(index) {
      eventBus.$emit('changeSide', index);
    },
  }
}
</script>

Managecontent.vue

<template>
  <div class="manageContent">
    <ArticlesManage v-if="msg === '1'"></ArticlesManage>
    <comment-manage v-else-if="msg === '2'"></comment-manage>
  </div>
</template>
<script>
import {eventBus} from '@/main'

export default {
  name: "ManageContent",
  components: {
    AlgorithmManage,
    CommentManage
  },
  created() {
    eventBus.$on('changeSide', (message) => {
      this.msg = message
    })
    console.log(this.msg);
  },
}
</script>

Guess you like

Origin blog.csdn.net/qq_44614115/article/details/114106365