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>

你可能感兴趣的:(vue.js,前端,typescript)