Vue Router 路由跳转传参实践

本文详细介绍了如何在Vue项目中使用VueRouter进行动态路由匹配和查询参数的传递。通过配置路由,从当前组件传参至目标组件,并展示了接收参数的方法。同时,文中还讨论了在路由嵌套时如何处理页面刷新策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Vue Router 路由跳转传参实践

一、动态路由匹配

1、路由配置

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'Hello',
    component: Hello,
  },
  {
      path: '/next-page/:message',
      name: 'NextPage',
      component: NextPage,
  },
];

2、当前组件:传参

<template>
  <button @click="toNextPage">toNextPage</button>
</template>

<script setup lang="ts">
import {useRouter} from 'vue-router';
// 得到 router 对象
const router = useRouter();
// 页面跳转
const toNextPage = () => {
  router.push({name: 'NextPage', params: {message: "基本字符串"}});
}
</script>

3、跳转目标组件:接收参数

<template>
  <h1>NextPage</h1>
  <h1>基本数据:{{ route.params.message }}</h1>
</template>

<script setup lang="ts">
import { useRoute } from "vue-router";
import {onMounted} from "vue";
const route = useRoute();
</script>

4、运行结果

image-20230415164331534

5、路由嵌套刷新页面策略

<template>
  <h1>NextPage</h1>
  <h1 :key="thisVersion">基本数据:{{ route.params.message }}</h1>
</template>

<script setup lang="ts">
import { useRoute } from "vue-router";
import {ref, watch} from "vue";
const route = useRoute();
// 当前版本
const thisVersion = ref(0);
// 监听参数变化,更新版本,刷新组件(大致写法,未测试)
watch(() => route.params.message, () => {
  thisVersion.value ++;
})
</script>

二、查询参数

1、路由配置

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'Hello',
    component: Hello,
  },
  {
      path: '/next-page',
      name: 'NextPage',
      component: NextPage,
  },
];

2、当前组件:传参

<template>
  <button @click="toNextPage">toNextPage</button>
</template>

<script setup lang="ts">
import {useRouter} from 'vue-router';
// 得到 router 对象
const router = useRouter();
// 页面跳转
const toNextPage = () => {
  router.push({name: 'NextPage', query: {message: "基本字符串", name: "訾博"}});
}
</script>

3、跳转目标组件:接收参数

<template>
  <h1>NextPage</h1>
  <h1>基本数据:{{ route.query.message }}</h1>
  <h1>基本数据:{{ route.query.name }}</h1>
</template>

<script setup lang="ts">
import { useRoute } from "vue-router";
const route = useRoute();
</script>

4、运行结果

image-20230415165257246

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值