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 兄弟組件(平級)通訊的實現代碼,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對幫客之家網站的支援!