注意:从Vue Router的2022-8-22 更新后,我们使用param传参在新页面无法获取数据。可以有其他解决办法:

1、使用query方式传参

注意query传参只能用路由表中的path,不是name,并且所有参数都会显示在URL地址上。

2、使用 History API 方式传递和接收

在跳转前的页面使用 state 参数,获取通过history.state.参数名

代码示例

Home页面

Home


{{ msg }}import {Check,Edit} from '@element-plus/icons-vue'import {ref,onMounted} from 'vue'import { useRouter,useRoute } from 'vue-router'let router = useRouter()//等同于vue2中的this.$routerconst route = useRoute()const EditHandle = () =>{window.open('http://127.0.0.1:5173/about','_blank')}const CheckHandle = () =>{router.push({ path: '/about', query: { plan: 'private' } })}let msg = ref()onMounted(() => {msg.value = history.state.name})

About页面

About-------{{ msg }}
import {Message,Star} from '@element-plus/icons-vue'import {ref,onMounted} from 'vue'import { useRoute, useRouter } from 'vue-router'; //2:定义变量const route = useRoute();const router = useRouter()let msg = ref()onMounted(() => {msg.value = route.query.plan})const MessageHandle = () =>{router.push({name:'home',state:{name:'张三'}})}const StarHandle = () =>{}

router/index.ts

import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';export const publicRoutes: Array = [{path: '/',name: 'home',component: () => import('../views/Home.vue')},{path: '/about',name: 'about',component: () => import('../views/About.vue')}];const router = createRouter({history: createWebHistory(),routes: publicRoutes});export default router

main.ts

import { createApp } from 'vue'import './style.css'import ElementPlus from 'element-plus'import 'element-plus/dist/index.css'import App from './App.vue'import router from './router'createApp(App).use(ElementPlus).use(router).mount('#app')

package.json

{"name": "vue_router_ts","private": true,"version": "0.0.0","type": "module","scripts": {"dev": "vite","build": "vue-tsc && vite build","preview": "vite preview"},"dependencies": {"element-plus": "^2.3.9","vue": "^3.3.4","vue-router": "^4.2.4"},"devDependencies": {"@vitejs/plugin-vue": "^4.2.3","typescript": "^5.0.2","vite": "^4.4.5","vue-tsc": "^1.8.5"}}