vue使用bus进行父子组件传值,以及解决bus多次触发的问题

新建一个bus.js文件

// bus.js
import Vue from 'vue'
export default new Vue;

子组件

<template>
	<button @click="handleClick">给父组件传值</button>
</template>

<script>
import Bus from './bus.js'
export default {
  name: "children",
  methods:{
      handleClick(){
          Bus.$emit('open','传的测试的值')
      }
  },
  
};
</script>

父组件

<template>
	<children />
</template>

<script>
import childrenfrom './children'
import Bus from './bus.js'
export default {
  name: "parent",
  created(){
      Bus.$on('open',(val)=>{
        console.log(`接受到子组件的值${val}`)
      });
  },
};
</script>

递归组件$emit多层点击不生效的时候也可以使用这个方法

解决bus多次触发的问题

在需要接收值的组件中修改代码

    created(){
    	Bus.$off('open') 
    	Bus.$on('open',(val)=>{
        	
      	});
    }

路由返回的时候使用bus传值,数据不更新的问题

// 如果遇到使用$router.go(-1)返回的时候,传值不更新的时候,在传值页面的销毁方法中destroyed()来进行传值

 // 这是传值页面
destroyed(){
    this.$bus.$emit('selectAddress',this.tshAddressStr)
},
methods:{
	selectAddress(item){
          console.log(item)
          this.tshAddressStr = item.address
          this.$router.go(-1)
       
    },
}

// 接收值的页面在created()方法中接收传过来的值

// 这是接收值的页面
created(){
        this.$bus.$off('selectAddress') 
        this.$bus.$on('selectAddress',(val)=>{
            this.addressaaa = val
        });
},
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值