VUE路由器 - 设置默认查询参数
我正在实施分页列表。因此,我正在使用查询参数,例如?size = 10
。此查询参数需要始终在我的URL内(例如 /home?size = 2)。
此Apporach无法正常工作:
const routes = [{ path: "/home", query: { size: "10" }, components: MyPage }];
const router = createRouter({
history: createWebHistory(),
routes,
});
我认为它正在用一些参数实例化路线。查看Vue DevTools的路由部分向我展示了一个空的查询对象:
$route:/home
fullPath:"/home"
path:"/home
query:Object (empty)
hash:""
name:undefined
params:Object (empty)
matched:Array[0]
meta:Object (empty)
redirectedFrom:undefined
href:"/home
如何将默认查询参数设置为我的路由?
I'm implementing an paginated list. Therefore I'm using query parameters like ?size=10
. This query paramter needs to be always inside my URL (like /home?size=2).
This apporach is not working:
const routes = [{ path: "/home", query: { size: "10" }, components: MyPage }];
const router = createRouter({
history: createWebHistory(),
routes,
});
I thought it is instantiating the route with some parameters. Looking into the Routing section of vue devtools shows me an empty query object:
$route:/home
fullPath:"/home"
path:"/home
query:Object (empty)
hash:""
name:undefined
params:Object (empty)
matched:Array[0]
meta:Object (empty)
redirectedFrom:undefined
href:"/home
How can I set a default query param to my route?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是使用
theeach
navigationguard的建议:这个想法是在不存在的情况下添加
size
的默认查询参数。Here is a proposal using the
beforeEach
NavigationGuard:The idea is to add to the route a default query parameter for
size
when it is not there.正确实现此目的的唯一方法而不定义每个
router.push()
中的默认值可能是导航gurads 。您可以使用它们来获取当前在URL中的查询参数,添加所需的默认查询 - 帕拉姆,然后返回新路由。尽管我不会这样做,但这可能是实现这一目标的最简单方法。
如果您想通过
The only way to achieve this properly without defining the default value in every
router.push()
is probably with Navigation Gurads. You can use them to get the query-parameters that are currently in the url, add the default query-params you need and then return the new route.Though I would not do it, this is probably the easiest way to achieve this.
And if you want to make them customizable via pinia/vuex you would need to set up a store and make a user input to change the setting.