参考这个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监听要建立起来。大家自己去百度代码,目前这里能用为主。
主要我参考了好多代码教程,感觉都不太能用