Vue3中使用组合式API通过路由传值详解

在Vue 3中,使用组合式API来传递路由参数是一种常见的需求。Vue Router 是 Vue.js的官方路由管理工具,可以在不同的场景下通过多种方式传递和接收路由参数。下面将详细讲解几种常见的路由传值方式,并提供相应的代码示例。

目录

      • [1. **通过路由参数传值(动态路由参数)**](#1. 通过路由参数传值(动态路由参数))
      • [2. **通过查询参数传值(URL查询字符串)**](#2. 通过查询参数传值(URL查询字符串))
      • [3. **通过 `state` 传值(使用 `router.push` 或 `router.replace`)**](#3. 通过 state 传值(使用 router.pushrouter.replace)
      • [4. **通过 `props` 传值(配合路由的 `props` 配置)**](#4. 通过 props 传值(配合路由的 props 配置))
      • [5. **总结**](#5. 总结)

1. 通过路由参数传值(动态路由参数)

路由参数是一种最常用的传值方式,通常用于 URL 路径中。例如,某个页面需要根据用户 ID 来加载数据。

使用场景:
  • 根据路由参数(如用户ID)显示不同的数据或组件。
代码示例:

定义路由(router/index.js

js 复制代码
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import UserProfile from '../views/UserProfile.vue';

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/user/:id',  // 使用动态路由参数
    name: 'UserProfile',
    component: UserProfile
  }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

export default router;

传参方式

如果你的路由是命名的,可以使用 name 属性来导航,并传递参数。

javascript 复制代码
import { useRouter } from 'vue-router';
const router = useRouter();
router.push({ name: 'user', params: { id: 123 } })

在组件中使用路由参数(UserProfile.vue

vue 复制代码
<template>
  <div>
    <h1>User Profile</h1>
    <p>User ID: {{ userId }}</p>
  </div>
</template>

<script setup>
import { useRoute } from 'vue-router';

// 获取路由对象
const route = useRoute();

// 从路由中获取动态参数
const userId = route.params.id;
</script>

访问 URL:

复制代码
http://localhost:8080/user/123

2. 通过查询参数传值(URL查询字符串)

查询参数通常用于传递不属于路径的一些附加信息,适合用于过滤、分页等场景。

使用场景:
  • 向一个页面传递一些过滤条件、分页信息等。
代码示例:

定义路由(router/index.js

js 复制代码
import { createRouter, createWebHistory } from 'vue-router';
import SearchResults from '../views/SearchResults.vue';

const routes = [
  {
    path: '/search',
    name: 'SearchResults',
    component: SearchResults
  }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

export default router;

传参方式

如果你的路由是命名的,可以使用 name 属性来导航,并传递参数。

javascript 复制代码
import { useRouter } from 'vue-router';
const router = useRouter();
router.push({ path: '/register', query: { plan: 'private' } })

在组件中使用查询参数(SearchResults.vue

vue 复制代码
<template>
  <div>
    <h1>Search Results</h1>
    <p>Search Query: {{ searchQuery }}</p>
  </div>
</template>

<script setup>
import { useRoute } from 'vue-router';

// 获取查询参数
const route = useRoute();
const searchQuery = route.query.q;
</script>

访问 URL:

复制代码
http://localhost:8080/search?q=vue3

3. 通过 state 传值(使用 router.pushrouter.replace

通过 router.pushrouter.replace 方法,除了可以传递路径、查询参数外,还可以使用 state 来传递一些临时的状态数据。这种方式非常适合传递一些短期的、不需要在 URL 中显示的值。

使用场景:
  • 在路由跳转时传递一些临时的数据,比如在表单提交后跳转到详情页,并传递表单数据。
代码示例:

跳转时使用 state 传值(在组件中使用 router.push

vue 复制代码
<template>
  <div>
    <button @click="goToUserProfile">Go to User Profile</button>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router';

const router = useRouter();

const goToUserProfile = () => {
  router.push({ 
    name: 'UserProfile',
    params: { id: '123' },
    state: { fromDashboard: true }
  });
};
</script>

在目标组件中获取 stateUserProfile.vue

vue 复制代码
<template>
  <div>
    <h1>User Profile</h1>
    <p>User ID: {{ userId }}</p>
    <p v-if="fromDashboard">Navigated from Dashboard</p>
  </div>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router';

// 获取路由参数
const route = useRoute();
const userId = route.params.id;

// 获取路由状态
const router = useRouter();
const fromDashboard = router.currentRoute.value.state?.fromDashboard;
</script>

4. 通过 props 传值(配合路由的 props 配置)

Vue Router 支持将路由参数直接作为 props 传递给组件。这对于需要从路由中解耦组件逻辑的情况非常有用。

使用场景:
  • 将路由参数直接作为组件的 props 传递,减少路由与组件之间的耦合。
代码示例:

定义路由(router/index.js

js 复制代码
import { createRouter, createWebHistory } from 'vue-router';
import UserProfile from '../views/UserProfile.vue';

const routes = [
  {
    path: '/user/:id',
    name: 'UserProfile',
    component: UserProfile,
    props: true  // 开启 props 传递
  }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

export default router;

在组件中接收 propsUserProfile.vue

vue 复制代码
<template>
  <div>
    <h1>User Profile</h1>
    <p>User ID: {{ id }}</p>
  </div>
</template>

<script setup>
// 接收路由参数作为 props
defineProps({
  id: String
});
</script>

5. 总结

在 Vue 3 中,可以通过不同的方式在路由之间传递值,选择哪种方式取决于具体的使用场景:

  • 动态路由参数:适用于需要根据 URL 动态改变内容的场景。
  • 查询参数:适用于传递额外的过滤条件或分页信息。
  • state:适用于传递不需要展示在 URL 中的临时数据。
  • props:适用于将路由参数直接作为组件的 props,简化组件的逻辑。

这些传值方法可以根据实际需求组合使用,以提供更灵活的路由管理和数据传递机制。

相关推荐
转转技术团队20 小时前
WebNN:让 AI 推理在浏览器中“零距离”运行
前端
刀法如飞20 小时前
TypeScript 数组去重的 20 种实现方式,哪一种你还不知道?
前端·javascript·算法
IT_陈寒20 小时前
Vite热更新失效?你可能漏了这个小细节
前端·人工智能·后端
海石20 小时前
面试官:说一下你现在使用的 AI IDE,什么,JoyCode 是什么?
前端·ai编程
彩票管理中心秘书长21 小时前
一次搞懂:在Vue里用Showdown渲染Markdown+KaTeX数学公式
前端
m0_7381207221 小时前
应急响应(重点)——记一次某公司流量应急溯源分析(附带下载链接)
服务器·前端·数据库·安全·web安全·网络安全
前端Hardy21 小时前
pnpm 11.0 正式登场:安装起飞、安全拉满、彻底告别 npm 依赖
前端
PILIPALAPENG21 小时前
第4周 Day 1:智能体记忆系统——给 Agent 一个"大脑"
前端·人工智能·python
_风满楼21 小时前
TDD实战-会议室冲突检测的红绿重构循环
前端·javascript·算法
Rkgua21 小时前
JS中的惰性函数基本介绍
前端·javascript