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>
  • 相关阅读:
    struts2 ajax传值
    s:iterator遍历
    JavaScript闭包
    组合继承与寄生组合式继承
    JSP EL表达式详细介绍
    js判断字符串是否包含中文或英文
    jQuery 中 jQuery(function(){})与(function(){})(jQuery) 的区别
    HTML5--新增结构元素(2)
    HTML5--新增全局属性(1)
    nodejs的安装配置(nvm-windows)
  • 原文地址:https://www.cnblogs.com/BlingSun/p/7866911.html
Copyright © 2011-2022 走看看