vue3路由传参获取不到params,获取到为空

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

1、使用query方式传参

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

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

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

代码示例

Home页面


About页面


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"
  }
}

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