实现功能:页面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页面中看到的效果如下: