zoukankan      html  css  js  c++  java
  • Vue 兄弟组件通过事件广播传递数据

    非父子组件传值

    通过事件广播实现非父子组件传值
    1.新建js,引入并实例化Vue
      import Vue from 'vue'
      var VueEvent = new Vue();
      export default VueEvent;
    2.子组件A中引入VueEvent,并广播事件
      import VueEvent from '../model/VueEvent.js'
      VueEvent.$emit('to-news',this.msg);
    3.子组件B中引入VueEvent,并监听事件
      import VueEvent from '../model/VueEvent.js'
      VueEvent.$on('to-news',data=>{console.log(data);});

    示例代码

    import Vue from 'vue'
    
    var VueEvent = new Vue();
    
    export default VueEvent;
    <template>
    <div id="home">
        <button @click="sendMsg()">我来触发事件</button>
    </div>
    </template>
    <script>
    import VueEvent from "../models/VueEvent.js";
    export default {
      data() {
        return {
          msg: "我是Home的msg"
        };
      },
      methods: {
        sendMsg() {
          VueEvent.$emit("tonews", this.msg);
        }
      }
    };
    </script>
    <style>
    </style>
    <template>
    <div id="news">
        我来接受事件--{{msg}}
    </div>
    </template>
    <script>
    import VueEvent from "../models/VueEvent.js";
    export default {
      data() {
        return {
          msg: "我是News的msg"
        };
      },
      mounted() {
        VueEvent.$on("tonews", res => {
          this.msg = res;
        });
      }
    };
    </script>
    <style>
    </style>
    <template>
      <div id="app">
       <v-home></v-home>
       <hr />
       <v-news></v-news>
      </div>
    </template>
    
    <script>
    import Home from "./components/Home.vue";
    import News from "./components/News.vue";
    export default {
      name: "app",
      data() {
        return {
          msg: "Welcome to Your Vue.js App"
        };
      },
      components: {
        "v-home": Home,
        "v-news": News
      }
    };
    </script>
    
    <style lang="scss">
    </style>
  • 相关阅读:
    一些平行模块化软件架构的坑
    qsub|pasta|
    open 管道用法|Getopt::Long
    Estimating Gene Frequencies| method of maximum likelihood|point estimate
    定义变量|dirname|basename|printf
    Linkage Disequilibrium|D‘|r2
    linkage disequilibrium|linkage equilibrium
    Sex linkage
    Different Gene Frequencies in the Two Sexes
    Overlapping generations model
  • 原文地址:https://www.cnblogs.com/chenyishi/p/9164386.html
Copyright © 2011-2022 走看看