vue 之 事件总线(订阅者模式,非父子间的数据传递)

如下图

 在这个马路上,有一辆bus在来回的接送,从a发布bus.$emit('aaa'),然后在c订阅bus.$on('aaa')

实例案例代码

app.vue

<template>
  <div id="app">
    <big-son></big-son>

    <hr />
    <small-son></small-son>
  </div>
</template>

<script>
import BigSon from "./components/BigSon";
import SmallSon from "./components/SmallSon";
export default {
  name: "App",
  components: {
    BigSon,
    SmallSon,
  },
};
</script>

<style></style>

main.js

import Vue from "vue";
import App from "./App.vue";

Vue.config.productionTip = false;

//1.创建一个事件总线
let bus = new Vue();
Vue.prototype.bus = bus;
//一个组件对一个实例

new Vue({
  render: (h) => h(App),
}).$mount("#app");

  

 

BigSon.vue

<template>
  <div>
    <h2>大儿子</h2>
    媳妇: <input type="text" v-model="wife" /><button @click="send">
      点击
    </button>
  </div>
</template>
<script>
测试玩的 import Vue from "vue"; let bus2 = new Vue(); Vue.prototype.bus2 = bus2; export default { name: "BigSon", data() { return { wife: "", }; }, methods: { send() { //2发布 this.bus.$emit("aaa", this.wife); this.bus2.$emit("bbb", this.wife); }, }, }; </script> <style></style>

SmallSon.vue

<template>
  <div>
    <h2>小儿子</h2>
    嫂子:xxx
  </div>
</template>
<script>
export default {
  name: "SmallSon",
  created() {
    //3订阅
    this.bus.$on("aaa", (res) => {
      console.log("开心的接受", res);
    });
    this.bus2.$on("bbb", (res) => {
      console.log("开心的接受2", res);
    });
  },
};
</script>
<style></style>

  

怎么理解订阅者模式呢?

原文地址:https://www.cnblogs.com/zmztya/p/14466620.html