页面简单传参
#简单的情景:你需要在帖子主页传递参数给帖子详情页面,携带在主页获得的帖子ID。你有以下几种传递方法#
#使用Vue3 + TS#
1. 通过 URL 参数传递(Query 参数)
这是最简单、最常用的方法,ID 会显示在 URL 中的 ? 后面
// 在 Post.vue 或其他组件中
const handleClick = () => {
router.push({
path: '/forum/post-detail',
query: { id: postId } // 这里的 postId 是你要传递的 ID
})
}
生成的 URL 会像这样:/forum/post-detail?id=123456
在 post-detail 页面中获取参数:
// 在 PostDetail.vue 中
import { useRoute } from 'vue-router'
const route = useRoute()
const postId = route.query.id // 获取传递的 ID
console.log('帖子ID:', postId)
// 使用 ID 获取帖子详情
onMounted(async () => {
if (postId) {
await getPostDetail(postId)
}
})
2. 通过路径参数传递(Path 参数)
这种方式 ID 直接集成到 URL 路径中,更符合 RESTful 设计。
首先需要在路由配置中定义参数:
// 在 router/index.js 中
const routes = [
{
path: '/forum/post-detail/:id',
name: 'PostDetail',
component: () => import('@/pages/forum/PostDetail.vue')
}
]
然后在组件中导航:
// 在 Post.vue 中
const handleClick = () => {
router.push({
path: `/forum/post-detail/${postId}` // 直接拼接到路径中
})
// 或者使用命名路由(更推荐)
router.push({
name: 'PostDetail',
params: { id: postId }
})
}
生成的 URL 会像这样:/forum/post-detail/123456
在 post-detail 页面中获取参数:
// 在 PostDetail.vue 中
import { useRoute } from 'vue-router'
const route = useRoute()
const postId = route.params.id // 从路径参数中获取 ID
3. 通过状态对象传递(不显示在 URL 中)
如果你不希望 ID 显示在 URL 中,可以使用 router 的 state 选项:
// 在 Post.vue 中
const handleClick = () => {
router.push({
path: '/forum/post-detail',
state: { postId: postId } // 通过 state 传递数据
})
}
在 post-detail 页面中获取:
// 在 PostDetail.vue 中
import { useRouter } from 'vue-router'
const router = useRouter()
const postId = router.currentRoute.value.state?.postId
// 注意:刷新页面后 state 会丢失!
二、如何选择使用场景
场景 | 推荐方式 | 理由 |
---|---|---|
传递资源 ID 或必要参数 | URL 路径参数(Params) | URL 直观,SEO 友好 |
分页、搜索等可选参数 | 查询参数(Query) | 灵活,参数可选 |
临时传递敏感数据(如表单) | 路由状态(State) | 不暴露 URL,内存存储安全 |
需要持久化的数据(如登录态) | 本地存储(LocalStorage) | 数据持久化,刷新不丢失 |
跨组件共享复杂数据 | 全局状态管理(Vuex/Redux) | 集中管理,避免层层传递 |