在练习尚品汇的过程中遇到的一个问题
老师让我们合并params和query参数,需要完成的需求如下
当点击联动框时跳转到search路由,同时带着点击组件搜到的query参数,然后在搜索框中搜索词条,词条转为params参数也要带着,即现在$route中既有query参数也有params参数
先搜索在点击联动框时同理分别接收到两个参数且要保证两个参数存在
先放上原本的代码和页面效果
在Header组件中
this.$router.push({
name: 'search',
params: { keyword: this.keyword || undefined },
})
在TypeNav中
let location = { name: "search" };
let query = { categoryName: categoryname };
location.query = query;
this.$router.push(location);
可以看到在原本的网页中,由于搜索按钮和联动框点击都会跳转到search组件,同时分别带着query和params参数,但并不会合并而是覆盖
接着我按照老师的步骤进行条件判断
当
r
o
u
t
e
中本来就有
q
u
e
r
y
属性时保留这个
q
u
e
r
y
属性,当
route中本来就有query属性时保留这个query属性,当
route中本来就有query属性时保留这个query属性,当route中本来就有params属性时保留这个params属性
在Header组件中
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 };
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,
}