您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)vue2.0中怎么實(shí)現(xiàn)兄弟組件通訊,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
1、前戲吧
個(gè)人理解:
這明顯是生活中弟弟打電話哥哥一樣,雙方都需要手機(jī),需要信號(hào)發(fā)射塔。
弟弟 => A組件
哥哥 => B組件
弟弟的手機(jī) => $emit發(fā)送數(shù)據(jù)
哥哥的手機(jī) => $on監(jiān)聽并接收數(shù)據(jù)
信號(hào)發(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> <h3>A組件</h3> <button v-on:click="spot">點(diǎn)一下就傳</button> </div> </template> <script> import bus from '../assets/ligature'; export default { methods: { spot: function() { //監(jiān)聽A組件中的spot,并發(fā)送數(shù)據(jù) bus.$emit("spot", ' 沒想到吧?。∥沂茿組件') } } } </script>
2.3、在src/components新建B.vue
<template> <div> <h3>B組件</h3> <p>結(jié)果:{{msg}}</p> </div> </template> <script> import bus from "../assets/ligature"; export default { data() { return { msg: "這TMD是默認(rèn)值除非你點(diǎ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 (地球),注冊(cè)這兩個(gè)組件,并添加這兩個(gè)組件的標(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>
關(guān)于vue2.0中怎么實(shí)現(xiàn)兄弟組件通訊就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。