vue bus.$emit触发第一次$on监听不到 顶部搜索框的实现

参考这个vue页面1,页面2的执行时间

直接上图效果,

1.顶部搜索栏,目前页面在首页的位置

2.输入球搜索,跳转到全部商品页面,实现商品搜索

代码

1.创建js

EventBus.js

import Vue from 'vue'
export const EventBus = new Vue()
// 为了不同页面

2.页面间引用A,B页面的Script位置

A页面

<script>
import { EventBus } from '../../assets/EventBus'
export default {

  data () {
    return {
      // 搜索关键字
      keywords: ''
    }
  },
  beforeDestroy () {
    this.searchClick()
  },
  methods: {
    // 点击搜索按钮
    searchClick () {
      EventBus.$emit('onSearchInput', this.keywords)
      this.$router.push('/allGoods')
    }
  }
}
</script>

B页面

  mounted () {
    this.queryInfo.query = EventBus.onSearchInput
    this.getGoodsList()
  },
  beforeCreate () {
    EventBus.$on('onSearchInput', (value) => {
      EventBus.onSearchInput = value
    })
  },
  created () {
    this.getGoodsList()
  },
  methods: {
    // 根据分页获取对应商品列表
    async getGoodsList () {
      const { data: res } = await this.$axios.get('/getAllGoods', {
        params: this.queryInfo
      })
      console.log(res)
      if (res.code !== 200) {
        return this.$message.error('获取商品列表失败!')
      }
      this.goodsList = res.result.goods
      this.total = res.result.total
      console.log(res.result.goods)
    }
}

getGoodsList()是我通过传入query(商品名称)来获取后端的商品

参考上面两个方法即可

  mounted () {
    this.queryInfo.query = EventBus.onSearchInput
    this.getGoodsList()
  },
  beforeCreate () {
    EventBus.$on('onSearchInput', (value) => {
      EventBus.onSearchInput = value
    })
  },

原理我是不是很清楚,什么vue是单页面的啥的,销毁周期,emit传递时,on监听要建立起来。大家自己去百度代码,目前这里能用为主。

主要我参考了好多代码教程,感觉都不太能用

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值