Pass values $emit and $on between VUE sibling components

  • Question: To add or view, you need to open a new page , which can be considered to be a re-walking of the life cycle of the Vue page. So you can't use VueX to store state.

  • Requirement: To add a new page, you need to determine whether the page is adding data or viewing data .

image.png

After clicking

image.pngThe left sideBar and the right are sibling components. You need to use an Id value to determine whether the new page is new data .

1. Add page pass value

Use Id = '' // Empty. Indicates as new. If it is not empty, it means to view

    medicalId = ''
    this.showAgedForm(medicalId)
复制代码

2. Passing values ​​between sibling components

use e m i t and emit and on

1. Build the bus Msg.js

Create Msg.js in js

import Vue from 'vue'
export default new Vue()
复制代码

2. Right page

Import Msg.js in js

import Msg from '../js/msg.js'
复制代码

Create a function to send data

methods:{
    sendAddFlag() { // 发送id
      Msg.$emit('medicalFlag', this.medical_id)
      console.log('传递出去的medical_id', this.medical_id)
    },
}
复制代码

Execute in created

this.sendAddFlag()
复制代码

3. The menu page on the left

Import Msg

import Msg from '../../../js/msg.js'
复制代码

Create a function to receive data

reseiveAddFlag() {
      var _this = this // 此处需要改变this的指向
      Msg.$on('medicalFlag', function(idFlag) {
        // console.log('传递过来的medical_id', idFlag)
        if (idFlag !== '') {
          // 传递过来的medical_id为''(空),则表示为新增的
          _this.sideHideOrShow = { display: 'block' }
        } else {
          _this.sideHideOrShow = { display: 'none' }
        }
      })
    },
复制代码

Execute in created

    this.reseiveAddFlag()
复制代码

4. Dynamic rendering of the page

<div class="sidebar" :style="sideHideOrShow">
复制代码

Guess you like

Origin juejin.im/post/7012979628285362207