面试题:Vue Router 中 params 和 query 有什么区别?

在 Vue Router 中,paramsquery 是两种不同的传递参数的方式,它们的主要区别如下:

1. 定义位置

  • Params: 通常在路由路径中定义,属于动态路由的一部分。例如:
{
path: '/user/:id',
component: User
}
  {
    path: '/user/:id',
    component: User
  }
{ path: '/user/:id', component: User }

这里的 :id 就是一个 param

  • Query: 通过 URL 的查询字符串传递,不属于路由路径的一部分。例如:
/user?id=123
  /user?id=123
/user?id=123

这里的 id=123 就是 query

2. URL 表现形式

  • Params: 参数直接嵌入在 URL 路径中。例如:
/user/123
  /user/123
/user/123

这里的 123params 参数。

  • Query: 参数以键值对的形式出现在 URL 的查询字符串中。例如:
/user?id=123&name=John
  /user?id=123&name=John
/user?id=123&name=John

这里的 id=123name=Johnquery 参数。

3. 获取方式

  • Params: 在组件中通过 this.$route.params 获取。例如:
this.$route.params.id // 获取 id 参数
  this.$route.params.id // 获取 id 参数
this.$route.params.id // 获取 id 参数
  • Query: 在组件中通过 this.$route.query 获取。例如:
this.$route.query.id // 获取 id 参数
  this.$route.query.id // 获取 id 参数
this.$route.query.id // 获取 id 参数

4. 是否必传

  • Params: 如果路由定义了 params,则必须传递,否则路由无法匹配。例如:
{
path: '/user/:id',
component: User
}
  {
    path: '/user/:id',
    component: User
  }
{ path: '/user/:id', component: User }

访问 /user 会失败,必须访问 /user/123

  • Query: 是可选的,不传递时不会影响路由匹配。例如:
/user
/user?id=123
  /user
  /user?id=123
/user /user?id=123

两者都可以正常匹配路由。

5. 使用场景

  • Params: 适合用于标识资源的唯一性,如用户 ID、文章 ID 等。
  • Query: 适合用于过滤、排序、分页等场景,如 ?page=1&sort=asc

6. SEO 影响

  • Params: 由于参数是路径的一部分,可能会影响 SEO,搜索引擎会将其视为不同的页面。
  • Query: 通常对 SEO 影响较小,搜索引擎可能会忽略查询参数。

示例

// 路由定义
const routes = [
{ path: '/user/:id', component: User },
{ path: '/profile', component: Profile }
]
// 导航
this.$router.push({ path: '/user/123' }); // params
this.$router.push({ path: '/profile', query: { name: 'John' } }); // query
// 获取参数
const userId = this.$route.params.id; // params
const userName = this.$route.query.name; // query
// 路由定义
const routes = [
  { path: '/user/:id', component: User },
  { path: '/profile', component: Profile }
]

// 导航
this.$router.push({ path: '/user/123' }); // params
this.$router.push({ path: '/profile', query: { name: 'John' } }); // query

// 获取参数
const userId = this.$route.params.id; // params
const userName = this.$route.query.name; // query
// 路由定义 const routes = [ { path: '/user/:id', component: User }, { path: '/profile', component: Profile } ] // 导航 this.$router.push({ path: '/user/123' }); // params this.$router.push({ path: '/profile', query: { name: 'John' } }); // query // 获取参数 const userId = this.$route.params.id; // params const userName = this.$route.query.name; // query

总结

  • Params 用于路径中的动态参数,通常用于标识资源。
  • Query 用于 URL 查询字符串中的参数,通常用于过滤、排序等操作。

理解这两者的区别有助于在实际开发中更好地设计路由和传递参数。

THE END
点赞13 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容