大家好,我想问一下关于 vue-router 的问题。 当我使用 vue 2 时,如果有一个页面不匹配,我会使用 path: '*' 转到我的 page404,但在 vue 3 中它已被替换为 '/:pathMatch(.)'在我尝试之后,控制台中的警告消失了,但我只是得到了一个空白页面,并且它没有指向我的 page404。我错过了什么?我是 vue 3 的新手
这是我正在使用的版本:
这是我的index.js
import { createRouter, createWebHistory, RouterView } from 'vue-router'
const routes = [
{
path: '/',
redirect: '/login',
component: RouterView,
children: [{
path: '/login',
component: () => import('@/views/login/Login.vue'),
}]
},
{
path: '/:pathMatch(.*)*',
component: () => import('@/views/page404/Page404.vue')
}
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
你可以尝试这样写
{
path: "/:pathMatch(.*)*",
redirect: "/404"
},
{
path: "/404",
name: "404",
component: () => import("@/views/page404/Page404.vue")
}
尝试使用
/:pathMatch(.*)
。
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: "/",
component: NotFound,
},
{
path: "/about",
component: AboutPage,
},
{
path: "/blogs",
component: BlogPage,
},
{
path: "/:pathMatch(.*)",
component: NotFound,
},
{
path: "/:pathMatch(.*)*",
component: NotFound,
},
],
});
/:pathMatch(.*)
和/:pathMatch(.*)*
之间的区别在于它们的前缀路由模式。
例如-
在
/foo/:pathMatch(.*)
中,这意味着它接受以'/foo'为前缀的/foo/any-miss-name
。但是当你尝试foo/any-miss-name/any-miss-name2
时,any-miss-name2
的前缀是any-miss-name
而不是/foo
。这就是为什么,它不会匹配并且无法工作。
在
/foo/:pathMatch(.*)*
中,这意味着它接受任何前缀模式(无需以 '/foo' 开头)。因此,每当您尝试 /foo/any-miss-name/any-miss-name2/any-miss-name(n)/
时,它都会匹配并完美运行。