實現功能:頁面A 跳轉到 頁面B,攜帶參數
路由router.ts
import { createRouter, createWebHistory } from "vue-router";const routes: RouteRecordRaw[] = [{path: "/demo/a",name: "aa",component: () => import("@/views/demo/A.vue")},{path: "/demo/b",name: "bb",component: () => import("@/views/demo/B.vue")},
];const router = createRouter({history: createWebHistory(),routes,strict: false,// 切換頁面,滾動到最頂部scrollBehavior: () => ({ left: 0, top: 0 })
});export default router;
A.vue
<template><div><button @click="fun">傳遞和接收參數</button></div>
</template><script setup lang="ts">
import { useRouter } from "vue-router";
//路由對象,用來進行路由跳轉
let router = useRouter();
const fun = () => {router.push({name: "bb",state: {data: "蘋果"}});
};
</script>
B.vue
<template><div><div>{{ stateData }}</div></div>
</template><script setup lang="ts">
//用來獲取路由對象的數據
const stateData = history.state; //通過History API接收
console.log("接收的參數:", stateData);
</script>
效果:
A頁面中單擊按鈕,在打開的B頁面中看到的效果如下: