合并params和query参数
场景:三级分类只有query参数,搜索框使用params参数。为了解决这个问题,文中在typeNav的index.vue和Head/index.vue分别进行了判断和处理,确保在不同的路径下合并params和query参数能正确合并并传递。
如何当点击联动框时跳转到search路由,同时带着点击组件搜到的query参数,然后在搜索框中搜索词条,词条转为params参数也要带着,即现在$route中既要有query参数又要有params参数。
在Header组件中:
源代码:
this.$router.push({name: 'search',params: { keyword: this.keyword || undefined },})
route中本来就有query属性时保留这个query属性,当route中本来就有params属性保留这个params属性。
修改之后:
let location = {name: 'search',params: { keyword: this.keyword || undefined },}if (this.$route.query) {location.query = this.$route.query}this.$router.push(location);
在TypeNav中
源代码:
let location = { name: "search" };let query = { categoryName: categoryname };location.query = query;this.$router.push(location);
修改之后:
let location = { name: "search" };let query = { categoryName: categoryname };// 判断:如果由跳转的时候如果由params参数,也进行传递if(this.$route.params){location.params = this.$route.params}// 合并路径和参数location.query = query;// 路由跳转this.$router.push(location);
当带着params属性点击联动框可以保留这个params属性,但带着query属性进行搜索时反而收不到的params属性。
应该在router文件中search的位置添加上params传参的占位符。
name: 'search',
path: '/search:keyword', // 占位符
component: Search,
meta:{isFooterShow:true,
}