How vue.js non-parent-child components communicate

refer to the code found on the Internet, but it has no effect (the code on the Internet is as follows):

create a new bus.js content as follows:
import Vue from "vue"
export default new Vue

a.vue
import Bus from". / bus.js"
triggers Bus.$emit ("msg", 123) in the event

b.vue
import Bus from". / bus.js"
receive in created or mounted hook:
Bus.$on ("msg", val = > {

)
this.nnum = val

})

is this all right?
is there a god who can explain it in detail

Mar.06,2021

the way to create a new bus is to create a new vue instance, which triggers the event through the $on listener function


bus_plugin.ts

import { Subject } from 'rxjs'
import Vue from 'vue'

const sub = new Subject<EventItem>()

interface EventItem {
  n: string;
  v: any;
}

const RxEvent = {
  install(Vue) {
    Vue.prototype.$rx_on = function (name: string, func: Function) {
      this.$subscribeTo(sub.filter(t => t.n === name).map(t => t.v), func)
    }

    Vue.prototype.$rx_emit = function (n: string, v) {
      sub.next({ n, v })
    }
  }
}

Vue.use(RxEvent)
< hr >

main.js

import Vue from 'vue'
import Rx from 'rxjs/Rx'
import VueRx from 'vue-rx'
import 'bus_plugin.ts'

Vue.use(VueRx, Rx)
< hr >

component.vue

export default {
  created() {
    this.$rx_on('event1', this.func1)
  },
  methods: {
    func1(v) {
      console.log(v)
    },
    emit() {
      this.$rx_emit('event1', 1)
    }
  }
}

ide/components.html-sharp%E9%9D%9E%E7%88%B6%E5%AD%90%E7%BB%84%E4%BB%B6%E7%9A%84%E9%80%9A%E4%BF%A1" rel=" nofollow noreferrer "> official documents

Communication between non-parent and child components

sometimes communication is also required between two components that are not in a parent-child relationship. In a simple scenario, you can use an empty Vue instance as the event bus:

var bus = new Vue()
//  A 
bus.$emit('id-selected', 1)
//  B 
bus.$on('id-selected', function (id) {
  // ...
})

if you are referring to sibling component communication, poke hard:


you can refer to my article vue non-parent-child component communication . If you have any problems, you can continue to communicate


this way is OK, but you need to modify it. The number of values passed will increase from 0 to https://www.jianshu.com/p/fde.

.
Menu