vue如何在路由中配置404页面

如何在路由中配置404页面

/router/index.js中,

由于路由是从上到下执行的,只要在路由配置中最后面放通配符*号就可以了,例如:

路由文件/router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Index from '@/view/index/index.vue'
import test1 from '@/view/test/test1.vue'
import test2 from '@/view/test/test2.vue'
import notFount from '../view/404/index.vue'


Vue.use(Router)

export default new Router({
    
    
  routes: [{
    
    
      path: '/',
      name: 'Index',
      component: Index,
      children: [{
    
    
        path: '/',
        name: 'HelloWorld',
        component: HelloWorld
      }, {
    
    
        path: '/test1',
        name: 'test1',
        component: test1
      }, {
    
    
        path: '/test2',
        name: 'test2',
        component: test2
      }]
    }, {
    
    
      path: '/test1',
      name: 'test1',
      component: test1
    },
    {
    
    
      path: '*',
      name: '404',
      component: notFount
    }
  ]
})

404页面 /404/index.vue

<template>
  <div>
    <h1>404!</h1>
  </div>
</template>

<script>
export default {
    
    };
</script>

<style>
</style>

效果:
我们在http://localhost:8080/#/后面输入其他路由,就会导入404页面
在这里插入图片描述
注意,是在/#/后面输入乱码,在#前面是不行的,因为/#/后面才是我们的默认初始路由,为什么会有/#/,这个我们最后会讲到。

问题

尝试在url中输入其他的路由来看404页面效果时,我遇到一个问题,就是不管在路由的#之前输入什么,最后都会进入默认路由的页面,一度让我以为在路由文件最后面放通配符是无效的,或者我的写法有问题。可是搜了很多后发现,写法上并没有不妥,后面我就发现路由里的#是有来历的。

项目生成的地址http://localhost:8080/#/,后面的/#/去不掉。这是路由的hash和history之分,默认是hash模式,会有#,大型框架的路由系统大多都是哈希实现的,把mode改成history,就没了。

参考

  • https://www.imooc.com/qadetail/229672?lastmedia=1
  • https://www.jianshu.com/p/9207a196a595
  • https://www.cnblogs.com/lmm1010/p/13216836.html?utm_source=tuicool

猜你喜欢

转载自blog.csdn.net/weixin_45844049/article/details/114947263