bus(总线传值-非父子间传值)

bus.js

import Vue from 'vue'
export default new Vue

App.vue

<template>
  <div id="app">
    <button @click="passMsg">传你</button>
    <my-parent></my-parent>
  </div>
</template>

<script>
import bus from "./util/bus";
import MyParent from "./views/Parent";
export default {
  components: {
    MyParent
  },
  methods: {
    passMsg() {
      bus.$emit("msg", "i am from app");
    }
  }
};
</script>
<style>
</style>

Child.vue

<template>
  <div>
    <h2>Child--{{childMsg}}</h2>
  </div>
</template>

<script>
import bus from "../util/bus";
export default {
  data() {
    return {
      childMsg: ""
    };
  },
  mounted() {
    bus.$on("msg", val => {
      this.childMsg = val;
    });
  }
};
</script>

<style>
</style>
posted @ 2020-03-29 17:30  xl4ng  阅读(783)  评论(0编辑  收藏  举报