我正在尝试重定向到使用router.beforeEach全局挂钩未找到的页面上的404.html ,但没有太大成功(使用Vue和Vue-Router1.0):
router.beforeEach(function (transition) {
if (transition.to.path === '/*') {
window.location.href = '/404.html'
} else {
transition.next()
}
});
Run Code Online (Sandbox Code Playgroud)
404.html插入不存在的路径时,这不会重定向到页面,只是给我一个空片段.只有在硬编码some-site.com/*时,它才会重定向到预期的some-site.com/404.html
我确信这里有一些非常明显的东西,我忽略了,但我无法弄清楚是什么.
请注意,我正在寻找的是重定向到新页面,而不是重定向到另一个路由,这可以通过使用router.redirect这些片段轻松实现:
router.redirect({
'*': '404'
})
Run Code Online (Sandbox Code Playgroud)
在我身上router.map,我可以拥有以下内容:
router.map({
'/404': {
name: '404'
component: {
template: '<p>Page Not Found</p>'
}
}
})
Run Code Online (Sandbox Code Playgroud) 我正在将 Vue Router 与 Vue 3 一起使用,并尝试添加一个包罗万象的路由以在用户尝试访问无效 URL 时重定向用户。当我尝试使用通配符 (*) 时,我将以下错误记录到控制台:
Uncaught Error: A non-empty path must start with "/"
at tokenizePath (vue-router.esm.js?8c4f:975)
at createRouteRecordMatcher (vue-router.esm.js?8c4f:1106)
at addRoute (vue-router.esm.js?8c4f:1190)
at eval (vue-router.esm.js?8c4f:1335)
at Array.forEach (<anonymous>)
at createRouterMatcher (vue-router.esm.js?8c4f:1335)
at createRouter (vue-router.esm.js?8c4f:2064)
at eval (index.js?a18c:26)
at Module../src/router/index.js (app.js:1402)
at __webpack_require__ (app.js:854)
Run Code Online (Sandbox Code Playgroud)
我假设这是因为我没有在包含星号的路径前面加上“/”,但是如果我这样做,那么捕获全部不起作用。以下是我的路线:
imports...
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/user',
name: 'User',
// route level code-splitting
// this generates a separate chunk (user.[hash].js) …Run Code Online (Sandbox Code Playgroud) 你好,我有两个模板:
Main.vue404.vue
如果用户进入正常页面,Main.vue则应使用该模板,每个页面都有嵌套路由。如果用户输入不存在的页面,404.vue则应使用有错误的模板。我尝试了以下操作,但它总是显示 404 错误,除了localhost:8080/(根路径访问):路由器.js:
export default new Router({
mode: 'history',
routes: [{
path: '/',
name: 'main',
component: Main,
childrens: [{
path: '/',
name: 'Home',
components: {
default: () =>
import ('@/views/Home'),
leftInfo: () =>
import ('@/views/DashboardAdditionalInfo'),
rightInfo: () =>
import ('@/components/common/MyTicketsList')
}
},
{
path: 'dashboard',
name: 'Dashboard',
components: {
default: () =>
import ('@/views/Dashboard'),
leftInfo: () =>
import ('@/views/DashboardAdditionalInfo'),
rightInfo: () =>
import ('@/components/common/MyTicketsList')
}
}
] …Run Code Online (Sandbox Code Playgroud)