vue非父子组件之间值传递

非父子之间通过一个空的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>

 

posted @ 2017-11-20 16:27  申小贺  阅读(245)  评论(0编辑  收藏  举报