vue 非父子组件传值

页面A 

<template>
  <div class="hello">
    <h1 @click="store">{{ msg }}</h1>
  </div>
</template>
<script>
export default {
    name: 'myHello',
    data () {
      return {
        msg: '点我传递',
        selected:'',
        showCondition:'',

      }
    },
  methods:{
      store(){
         this.$router.push({path:'/myHello'})
    }
  },
  destroyed(){
    eventBus.$emit('test','我是新的');
  },
  beforeDestroy(){
//    eventBus.$emit('test','我是新的');
  }
}
</script>

页面A给页面B传值‘我是新的’,用eventBus,该eventBus注册在main.js里面,给下个页面传值的时候需要卸载destroyed或者beforeDestroy里面

window.eventBus = new Vue()

页面B

<template>
  <div class="hello">
    <h1 @click="getStore">{{ msg }}</h1>
    <h2 @click="touterChange">{{testText}}{{num}}</h2>
 </div>
</template>

<script>
export default {
    name: 'HelloWorld',
    data () {
      return {
        msg: '点我接收',
        selected:'',
        showCondition:'',
        testText:'旧的',
        val:'',
        num:1
      }
    },
  methods:{
      getStore(){
        this.testText = this.val;
        console.log(123);
        this.num += 1
      },
    touterChange(){
      this.$router.push({path:'/'})
    }
  },

  created(){
    var that = this;
    eventBus.$on('test',function (val) {
      that.testText = val
      that.val = val;
      console.log(val)
    })
  },
//在组件销毁的时候 注销掉监听的值
  beforeDestroy() {
    eventBus.$off('test')
  },
}
</script>

页面B created生命钩子里面监听取值,如果用路由方式跳转的页面,必须在beforeDestroy周期里面关掉监听的这个值,以免造成返回页面来回过程中触发多次监听事件

eventBus.$on接收
  (备注:如有不对的地方,欢迎大家指正)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值