1. 程式人生 > >vue 非父子組件傳值

vue 非父子組件傳值

pan eth con mit import title home ews script

 1 <template>    
 2     <div id="news">
 3     
 4        我是新聞組件
 5         <br>
 6 
 7        <button @click="emitHome()">給Home組件廣播數據</button>
 8 
 9         <br>
10     </div>
11 
12 </template>
13 
14 
15 <script>
16 //引入 vue實例
17     import VueEvent from ‘../model/VueEvent.js‘;
18 19 export default{ 20 data(){ 21 return { 22 msg:‘我是一個新聞組件‘ 23 } 24 }, 25 methods:{ 26 emitHome(){ 27 28 //廣播 29 30 VueEvent.$emit(‘to-home‘,this.msg) 31 }
32 33 }, 34 mounted(){ 35 36 VueEvent.$on(‘to-news‘,function(data){ 37 console.log(data); 38 }) 39 } 40 41 } 42 43 </script> 44 45 <style lang="scss" scoped> 46 47 </style>

上面是新聞組件

下面是home組件

 1 <template>
 2
<!-- 所有的內容要被根節點包含起來 --> 3 <div id="home"> 4 5 我是首頁組件 6 7 <br> 8 9 <button @click="emitNews()">給News組件廣播數據</button> 10 11 <br> 12 13 </div> 14 15 </template> 16 17 18 <script> 19 20 //引入 vue實例 21 22 23 import VueEvent from ‘../model/VueEvent.js‘; 24 25 export default{ 26 data(){ 27 return { 28 msg:‘我是一個home組件‘, 29 title:‘首頁111‘ 30 } 31 },methods:{ 32 33 emitNews(){ 34 //廣播數據 35 36 VueEvent.$emit(‘to-news‘,this.msg) 37 38 } 39 }, 40 mounted(){ 41 42 //監聽news 廣播的數據 43 VueEvent.$on(‘to-home‘,function(data){ 44 console.log(data); 45 }) 46 } 47 48 } 49 50 </script> 51 52 <style lang="scss" scoped> 53 54 55 56 </style>

下面是VueEvent.js

1 import Vue from ‘vue‘;
2 
3 
4 var VueEvent = new Vue()
5 
6 
7 
8 export default VueEvent;

vue 非父子組件傳值