注意:从Vue Router的2022-8-22 更新后,我们使用param传参在新页面无法获取数据。可以有其他解决办法:
1、使用query方式传参
注意query传参只能用路由表中的path,不是name,并且所有参数都会显示在URL地址上。
2、使用 History API 方式传递和接收
在跳转前的页面使用 state 参数,获取通过history.state.参数名
代码示例
Home页面
<template>
<h1>Home</h1>
<el-button @click="EditHandle" type="primary" :icon="Edit" circle />
<el-button @click="CheckHandle" type="success" :icon="Check" circle />
<br>
{{ msg }}
</template>
<script lang="ts" setup>
import {Check,Edit} from '@element-plus/icons-vue'
import {ref,onMounted} from 'vue'
import { useRouter,useRoute } from 'vue-router'
let router = useRouter() //等同于vue2中的this.$router
const 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
})
</script>
About页面
<template>
About-------{{ msg }}
<br>
<el-button @click="MessageHandle" type="info" :icon="Message" circle />
<router-link to="/">
<el-button @click="StarHandle" type="warning" :icon="Star" circle />
</router-link>
</template>
<script lang="ts" setup>
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 = () =>{
}
</script>
router/index.ts
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
export const publicRoutes: Array<RouteRecordRaw> = [
{
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"
}
}