本例中有一个搜索模块和主页模块,主页点击搜索,需要在搜索页展示,搜索页输入关键字搜索。
1. 在搜索模块保存 搜索需要携带的参数,在 beforemount 中整理携带的参数,然后在 mounted 中发起请求
export default {
data(){
return {
searchParams:{ // 发请求需要携带的参数
category1Id: "",
category21d: "",
category3Id: "",
categoryName:"",
keyword:"",
order: "", // 排序
pageNo: 1, // 分页
pageSize: 10, // 每一页展示的个数
props:[], // 平台售卖商品的参数
trademark:"", // 品牌
}
}
},
beforeMount(){
// 组件挂载完毕之前执行一次,得到 searchParams ,然后在 mounted 中再请求
Object.assign(this.searchParams,this.$route.query,this.$route.params)
},
mounted(){
// mounted 只会执行一次,而搜索请求因为内容不同是要发起多次请求,因此要把它封装一个函数,需要的时候就调用
// this.$store.dispatch("getSearchList",{})
this.getData()
},
}
2. 监听路由变化发起请求
输入关键字搜索:
router.js
{
path: '/search/:keyword?', // 加了一个问号,表示 params 可传可不传
name: 'Search',
component: Search,
meta:{show:true},
props:($route)=>{
return { keywords:$route.params.keyword }
}
}
search.vue
watch:{
// 监听路由信息是否发生变化,如果发生变化再次发请求
$route(){
this.searchParams.category1Id = undefined
this.searchParams.category2Id = undefined
this.searchParams.category3Id = undefined
Object.assign(this.searchParams,this.$route.query,this.$route.params)
this.getData()
}
}
搜索的方法:
goSearch(){
let location = {name:"Search",params:{keyword:this.keyword || undefined}}
if(this.$route.query.categoryName){ // 判断组件是否有 query 参数
location.query = this.$route.query // 将 query 参数添加到 location
// 携带了 query 参数和 params 参数跳转到 search 组件
}
this.$router.push(location)
}
该博客详细介绍了如何在Vue.js应用中实现搜索功能。通过在beforeMount和mounted钩子中处理参数,并监听路由变化以更新搜索请求。当用户在主页点击搜索或输入关键字时,搜索页面会展示相应结果。同时,使用watch监听路由变化,确保参数正确传递并触发新的搜索请求。
1665

被折叠的 条评论
为什么被折叠?



