Vue3+router动态传参

路由传参query、params以及动态路由传参

一、query传参

编程式导航 使用router.push 或者 router.replace 的时候,改为对象形式新增query 必须传入一个对象

二、params传参

编程式导航 使用router.push 或者 router.replace 的时候,改为对象形式并且只能使用name,path无效,然后传入params

三、动态传参

例如,我们可能有一个 User 组件,它应该对所有用户进行渲染,但用户 ID 不同。在 Vue Router 中,我们可以在路径中使用一个动态字段来实现,我们称之为 路径参数

 // router/index.ts

//引入路由对象
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";

//路由数组的类型 RouteRecordRaw
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: 'Login', //router-link跳转方式需要改变 变为对象并且有对应name
    component: () => import("../components/login.vue"),
  },
  {
    path: "/home/:id", // 动态路由参数
    name: 'Home',
    component: () => import("../components/home.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

export default router;

传参页面

<template>
  <div>
    Login
    <button @click="setUrlData(obj)">跳转传参</button>
  </div>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import { useRouter } from "vue-router";
const router = useRouter();
type H = {
  name: string;
  age: number;
};

let obj = reactive<H>({
  name: "zs",
  age: 18,
});

// query传参
// const setUrlData =(Item:H) => {
//     router.push({
//         path: '/home',
//         query: obj
//     })
// }

// 最新版本路由已经不支持 params传参
// const setUrlData =(obj:H) => {
//     router.push({
//         name: 'Home',
//         params: {
//             data:1
//         }
// })
// }

// 动态路由传参
const setUrlData = (obj: H) => {
  router.push({
    name: 'Home',
    params: {
      id: obj.age
    },
  });
};
</script>

<style scoped></style>

接收参数页面

<template>
    <div>
        Home
        <!-- {{route.query.name}} ---- {{route.query.age}} -->
        <!-- {{route.params.name}} ---- {{route.params.age}} -->
        {{route.params.id}}
    </div>
</template>

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

</script>

<style scoped>

</style>
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值