vue2.0 兄弟組件(平級)通訊的實現代碼,vue2.0組件

來源:互聯網
上載者:User

vue2.0 兄弟組件(平級)通訊的實現代碼,vue2.0組件

1、前戲吧

先看看前兩篇文章:

父組件傳給子組件

子組件傳給父組件

看圖 看圖 看圖!!!

 

個人理解:

這明顯是生活中弟弟打電話哥哥一樣,雙方都需要手機,需要訊號發射塔。

  • 弟弟 => A組件
  • 哥哥 => B組件
  • 弟弟的手機 => $emit發送資料
  • 哥哥的手機 => $on監聽並接收資料
  • 訊號發射塔 => 中間事件線
  • App.vue => 不用說都知道是地球

2、 代碼

2.1、在src/asstes下建立中間事件線ligature .js (注意尾碼.js)

import Vue from 'Vue'export default new Vue;

2.2、在src/components建立A.vue

<template> <div> <h2>A組件</h2> <button v-on:click="spot">點一下就傳</button> </div></template><script> import bus from '../assets/ligature'; export default { methods: { spot: function() { //監聽A組件中的spot,並發送資料 bus.$emit("spot", ' 沒想到吧!!我是A組件') } } }</script>

2.3、在src/components建立B.vue

<template> <div> <h2>B組件</h2> <p>結果:{{msg}}</p> </div></template><script> import bus from "../assets/ligature"; export default { data() { return { msg: "這TMD是預設值除非你點一下上面的按鈕" }; }, mounted() { var _this = this; //監聽A組件中的spot,並接受資料 bus.$on("spot", function(msg) { _this.msg = msg; }); } };</script><style>p{ font-size: 20px; color: darkcyan;}</style>

2.4、修改App.vue (地球),註冊這兩個組件,並添加這兩個組件的標籤

<template> <div id="app"> <A/> <hr> <B/> </div></template><script>import A from './components/A'import B from './components/B'export default { name: 'App', components: { A, B }}</script>

3、效果

 

總結

以上所述是小編給大家介紹的vue2.0 兄弟組件(平級)通訊的實現代碼,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對幫客之家網站的支援!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.