• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
逍遥汉
博客园    首页    新随笔    联系   管理    订阅  订阅

vue-兄弟组件传值

兄弟组件之间传值:

  兄弟之间的传递数据需要借助于事件中心,通过事件中心传递数据提供事件中心 var hub = new Vue()
  传递数据方,通过一个事件触发hub.$emit(方法名,传递的数据)
  接收数据方,通过mounted(){} 钩子中 触发hub.$on()方法名
  销毁事件 通过hub.$off()方法名销毁之后无法进行传递数据
  <div id="app">
    <!-- 注册两个全局组件 -->
    <Tom></Tom>
    <Jerry></Jerry>
  </div>
  <script>
    const eventBus = new Vue()
    // 组件Tom
    Vue.component('Tom',{
      // tom组件中定义一个自定义函数
      template:`<div>Tom:{{num}}<button @click="handle">click</button></div>`,
      data:function(){
        return{
          num:0
        }
      },
      methods:{
        handle(){
          // 通过自定义事件,用eventBus这个事件总线来调用$emit来触发Jerry组件中的事件
          eventBus.$emit('Jerry-box',5)
        }
      },
      mounted:function(){
        // 通过事件总线来添加一个添加事件,val为兄弟组件传递的参数
        eventBus.$on('Tom-box',val=>{
          this.num+=val;
        })
      }
    })
    // 组件Jerry
    Vue.component('Jerry',{
      template:`<div>Jerry{{num}}<button @click="handle">click</button></div>`,
      data:function(){
        return{
          num:0
        }
      },
      methods:{
        handle(){
          eventBus.$emit('Tom-box',2)
        }
      },
      mounted:function(){
        eventBus.$on('Jerry-box',val=>{
          this.num+=val;
        })
      }
    })
    const vm = new Vue({
      el:"#app",
    })
  </script>

 

时间如白驹过隙,忽然而已,且行且珍惜......
posted @ 2020-11-12 16:44  unfetteredman  阅读(429)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3