Vue3路由查询参数渲染异常:/mypage?id=hjhj未显示参数值
问题解决:Vue3路由查询参数无法渲染的问题
你的代码存在两个关键错误,导致查询参数无法正常显示:
错误点及修复方案
- 参数名称不匹配:你期望接收的是查询参数
id,但路由配置里却在映射route.query.foo,两者名称不一致,无法正确获取到id的值。 - 模板中错误使用
this:Vue模板的表达式上下文已经是组件实例,不需要通过this来访问props或数据,直接写变量名即可。
修正后的完整代码
router/index.js
修改路由的props配置,将查询参数id映射到组件的props上:
const isServer = typeof window === 'undefined'; const history = isServer ? createMemoryHistory() : createWebHistory(); const routes = [{ path: '/', name: 'Home', component: Home, }, { path: '/about', name: 'About', component: About, }, { path: '/mypage', name: 'mypage', component: MyPage, props: (route) => ({ // 把query里的id映射到组件的id props id: route.query.id }), } ]; const router = createRouter({ history, routes, }); export default router;
MyPage.vue
修改模板去掉this,并调整props的名称为id(保持和路由映射一致):
<template> <h2>Home</h2> <!-- 直接使用id变量,无需this --> <h3>{{ id }}</h3> </template> <script> export default { props: { id: { type: String, default: null, }, }, }; </script>
可选方案:如果想保留foo作为props名称
如果你不想修改props名称,也可以在跳转或访问时传入?foo=hjhj,同时保持路由里的foo: route.query.foo配置,模板里改为{{ foo }}即可,但这不符合你接收id参数的需求,更推荐上面的方案。
内容的提问来源于stack exchange,提问作者Pierre-Alexandre
相关产品推荐
相关产品推荐

