VueRouter4的捕获所有路由问题及解决方案

1,284 阅读1分钟

VueRouter4的捕获所有路由问题及解决方案

routes: [{
		path: "/home",
		name:"home",
		component: Home
	},{
		path: "/*",
		redirect: "/home"
	}]

以上路由器代码在Vue3跳转到其他页面时会无法产生效果,原因是Vue-Router3中的path: "/*"Vue-Router4中的匹配语法修改成了path: "/:pathMatch(.*)* 官方文档:捕获所有路由或 404 Not found 路由 同时也找到了可以使用path: "/:matchAll(.*),于是代码变成了这样

routes: [{
		path: "/home",
		name:"home",
		component: Home
	},{
		// path: "/:matchAll(.*)",
		path: "/:pathMatch(.*)*",
		redirect: "/home"
	}]

两种方法都可以用,不过都会报以下警告

vue-router.mjs:35 [Vue Router warn]: Discarded invalid param(s) "catchAll" when navigating. See github.com/vuejs/route… for more details.

所以在看了文档过后,得知在 Vue Router 4 对路由配置的使用进行了一些勘误,避免在重新加载页面后丢失参数等问题,警告路由配置中不能仅有pathname。 我个人倾向于是vue-router的开发者忘记了有重定向的情况,因为在代码中是有提到redirect不会配置props所以干嘛干嘛(写文的时候git打不开,也就没办法复制代码了,在packages/router/src/matcher/index.ts中有提到) 扯远了,将代码修改为以下方式,就不会再报错了

routes: [{
	path: "/:catchAll(.*)",
	// path: "/:pathMatch(.*)*",
	name:"home",
	component: Home
}]

如果确定需要重定向的话,可以采用以下方案 首先引入vue-router中的useRoute

import {useRouter} from "vue-router";

嗯……其实上面代码也可以不用,直接使用this.$router也行,我就是试试useRouter而已

routes: [{
		path: "/home",
		name:"home",
		component: Home
	},{
	path: "/:catchAll(.*)",
	component: {
		default: Home,
		redirect: {
			mounted(){
				let router = userRouter();
				// 其实就相当于
				// let router = this.$router;
				router.push({
					name: "/home"
				});
			}
		}
	}
}]

当然,也可以另外写个文件再import进来

<template><div></div></template>
<script>
export default {
    name: "RedirectComp",
    mounted(){
            this.$router.push({
                    name: "/home"
            });
    }
}
</script>
import RedirectComp from ".../RedirectComp";
import Home from ".../Home";
routes: [{
		path: "/home",
		name:"home",
		component: Home
	},{
	path: "/:catchAll(.*)",
	component: RedirectComp
}]