2024-09-18 15:08:22 +08:00

104 lines
2.2 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 路由传参方式
>面试题Vue 项目中前端路由传参方式有哪些?
1. 路径参数
2. 查询参数
3. 路由状态参数
4. 路由props参数
**1. 路径参数**
通过 params 获取路径参数
```js
const routes = [
{
path: '/users/:userId(\\d+)',
component: User
},
]
```
```js
// vue2
this.$route.params.userId;
// vue3
const route = useRoute()
const id = route.params.id
```
**2. 查询参数**
通过 URL 中的查询字符串传递的参数,以 ?key=value 的形式进行传递。
特点:可以传递多组参数
```js
// 使用 this.$router.push 传递查询参数
this.$router.push({ path: '/user', query: { id: '123' } });
// 获取参数
this.$route.query.id;
```
**3. 路由状态参数**
路由状态参数Route State Parameters是一种通过 router.push 或 router.replace 方法传递的参数,这些参数**不会在 URL 中显示**,而是在应用程序的**内存中进行传递**,此方式适合传递一些不希望在 URL 中公开显示的临时数据或敏感信息。
```js
// 传递状态参数
this.$router.push({ path: '/user', state: { id: '123' } });
// 获取参数
history.state.id;
```
**4. 路由props参数**
在路由配置中设置 props: true 或传递一个函数,将路由的 params 或 query 直接作为组件的 props 传递给子组件。
```js
const routes = [{
path: '/user/:id',
component: User,
props: true
}]
```
```vue
<script setup>
defineProps({
id: {
// ....
}
})
</script>
```
Vue3课程《细节补充 - 路由组件传参》
>面试题Vue 项目中前端路由传参方式有哪些?
>
>参考答案:
>
>Vue 项目中前端路由传参的方式主要有这么几种:
>
>1. 路径参数: 这种方式直观,路径直接反映参数的结构。适合用于需要在路径中明确表示的参数,如资源 ID。
>2. 查询参数:该方式可选参数使用方便,适合用于不确定的参数个数,或者需要在组件间传递较多的参数。
>3. 路由状态参数:参数不会出现在 URL 中,安全性更高,适合用于敏感信息的传递。
>4. 路由props参数参数直接以 props 形式传入,这样能删除组件对 $route 的直接依赖,达到与 $route 解耦的效果。
---
-EOF-