1、前戲吧
先看看前兩篇文章:
看圖 看圖 看圖!??!
個人理解:
這明顯是生活中弟弟打電話哥哥一樣,雙方都需要手機,需要信號發射塔。
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 兄弟組件(平級)通訊的實現代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
|
新聞熱點
疑難解答