vue2.0 兄弟組件(平級)通訊的實現(xiàn)代碼
1、前戲吧
先看看前兩篇文章:
看圖 看圖 看圖!??!
個人理解:
這明顯是生活中弟弟打電話哥哥一樣,雙方都需要手機,需要信號發(fā)射塔。
- 弟弟 => A組件
- 哥哥 => B組件
- 弟弟的手機 => $emit發(fā)送數(shù)據(jù)
- 哥哥的手機 => $on監(jiān)聽并接收數(shù)據(jù)
- 信號發(fā)射塔 => 中間事件線
- 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() { //監(jiān)聽A組件中的spot,并發(fā)送數(shù)據(jù) bus.$emit("spot", ' 沒想到吧??!我是A組件') } } } </script>
2.3、在src/components新建B.vue
<template> <div> <h2>B組件</h2> <p>結(jié)果:{{msg}}</p> </div> </template> <script> import bus from "../assets/ligature"; export default { data() { return { msg: "這TMD是默認(rèn)值除非你點一下上面的按鈕" }; }, mounted() { var _this = this; //監(jiān)聽A組件中的spot,并接受數(shù)據(jù) bus.$on("spot", function(msg) { _this.msg = msg; }); } }; </script> <style> p{ font-size: 20px; color: darkcyan; } </style>
2.4、修改App.vue (地球),注冊這兩個組件,并添加這兩個組件的標(biāo)簽
<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、效果
總結(jié)
以上所述是小編給大家介紹的vue2.0 兄弟組件(平級)通訊的實現(xiàn)代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Vue3中Composition?API和Options?API的區(qū)別
Vue3的Composition API和Options API是Vue.js框架中的兩種不同的API,本文主要介紹了Vue3中Composition?API和Options?API的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06Vue調(diào)試工具vue-devtools的安裝與使用
vue-devtools是專門調(diào)試vue項目的調(diào)試工具,安裝成功之后,右邊會出現(xiàn)一個vue,就可以在線可以調(diào)試vue了,下面這篇文章主要給大家介紹了關(guān)于Vue調(diào)試工具vue-devtools的安裝與使用的相關(guān)資料,需要的朋友可以參考下2022-07-07詳解vue + vuex + directives實現(xiàn)權(quán)限按鈕的思路
這篇文章主要介紹了詳解vue + vuex + directives實現(xiàn)權(quán)限按鈕的思路,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10elementUi vue el-radio 監(jiān)聽選中變化的實例代碼
這篇文章主要介紹了elementUi vue el-radio 監(jiān)聽選中變化,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-06-06