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

vue非父子組件之間值傳遞

eve return 傳遞 deb imp disable rom data ble

非父子之間通過一個空的vue實例作為事件總線,相當於一個中轉站。這個中轉站是所有組件都可以看到的,大家通過這個中轉站接收和觸發事件。

import Vue from vue
import App from ./App
import router from ./router

Vue.config.productionTip = false

/* eslint-disable no-new */

new Vue({
  el: #app,
  router,
   data:{
    
        eventHub:new Vue()
   
  },
  template: 
<App/>, components: { App } })

在main.js文件中,添加一個空的vue實例eventHub。該實例需要是全局的,因為要在各個組件之中使用,而在此定義可以作為一個全局變量。

在子組件中通過this.$root.eventHub獲取該實例。

在組件A中:

<script>

export default {
  name: header,
   data:function(){
     return {
         
     }
  },
  methods:{
     sbar:function(){
      
        
this.$root.eventHub.$emit(showbar,[1]); } } } </script>

在組件B中:

<script>
export default {
  name: slidebar,
  data:function(){
     return {
         bar:true
     }
  },  
 
  mounted:function(){
     this.$root.eventHub.$on(showbar,function(val){
         this.bar=true;
         console.log(val);
         
     }.bind(
this)) //這裏必須綁定this,否則報錯。我也不知道為什麽。 }, methods:{ nobar:function(){ this.bar=false; } } } </script>

vue非父子組件之間值傳遞