好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

解决vue项目路径不正确,自动跳转404的问题

vue项目路径不正确,自动跳转404

第一种方法

使用vuerouter钩子函数beforeEach,每次进行路由跳转时都进行判断,若页面不存在就跳转到404页面。

import Error from ' '
?
const router = new Router({
? ? routes:[
? ? ? ? name: 'error',
? ? ? ? path: '/error',
? ? ? ? component: Error
? ? ]
}
?
//beforeEach每次进行路由跳转时都会执行
router.beforeEach((to,from,next){
? ? if(to.matched.length === 0){
? ? ? ? from.path ? next({name: from.name}) : next('/error')
? ? }else{
? ? ? ? next()
? ? }
})
?
export default router

第二种

redirect重定向

?{ ? ? path: '/404', ? ? ??
? ? ? ?component: () => import('@/views/error-page/404'), ? ? ??
? ? ? ?hidden: true ? ??
? },?
? ??
//这个*匹配必须放在最后,将改路由配置放到所有路由的配置信息的最后,否则会其他路由path匹配造成影响。 ? ??
?{ ? ? path: '*',
? ? ? ?redirect: '/404',?
? ? ? ?hidden: true?
? }

vue路由判断跳转404页面

beforeEach函数 这是路由跳转前处理的函数

import PageNotFound from '@/views/pages/404.vue'
Vue.use(Router)
const routes=[
? {
? ? path: '*',
? ? name: 'PageNotFound',
? ? component: PageNotFound,
? },
]?
?
const router = new Router({
? mode: 'history',
? routes: routes
})
?
router.beforeEach((to, from, next) => {
? // ?从其他地方访问是否有这个地址
? ? if(to.matched.length == 0){
? ? ? from.path ? next({name: from.name}) : next('*')
? ? }
? ? next();
});

第二种方法就是重定向地址 同上

修改routes中的地址

? {
? ? path: '/404',
? ? name: 'PageNotFound',
? ? component: PageNotFound,
? },
? {
? ? path:'*',
? ? redirect:'/404'
? ?}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。 

查看更多关于解决vue项目路径不正确,自动跳转404的问题的详细内容...

  阅读:59次