zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    欧拉公式
    isap的一些想法
    错误合集
    Hello World
    PAT (Advanced Level) Practice 1068 Find More Coins
    PAT (Advanced Level) 1087 All Roads Lead to Rome
    PAT (Advanced Level) 1075 PAT Judge
    PAT (Advanced Level) 1067 Sort with Swap(0, i)
    PAT (Advanced Level) 1017 Queueing at Bank
    PAT (Advanced Level) 1025 PAT Ranking
  • 原文地址:https://www.cnblogs.com/BlingSun/p/7866911.html
Copyright © 2011-2022 走看看