• 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>
  • 相关阅读:
    Centos6.4 cobbler安装要点
    zabbix oracle监控插件orabbix部署安装
    CPP
    基于curl 的zabbix API调用
    oracle 存储过程
    sqlplus乱码
    Intent之对象传递(Parcelable传递对象和对象集合)
    IOS压缩解压缩
    深入浅出java静态代理和动态代理
    c语言用rand() 函数,实现random(int m)
  • 原文地址:https://www.cnblogs.com/BlingSun/p/7866911.html
Copyright © 2020-2023  润新知