Vue2和Vue3中如何设置404界面

前端开发   发布日期:2023年06月20日   浏览次数:540

这篇文章主要讲解了“Vue2和Vue3中如何设置404界面”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Vue2和Vue3中如何设置404界面”吧!

一.vue2

1.index.js

在此文件中,一般存放的都是我们的路由信息,我们经常使用path:'*'来进行捕获我们的路由,度过不存在那么我们就让它进行跳转至我们自定义的404页面。

  1. import Vue from 'vue'
  2. import Router from 'vue-router'
  3. import Homepage from '@/components/Homepage'
  4. Vue.use(Router)
  5. export default new Router({
  6. routes: [
  7. {
  8. path: '/',
  9. component: Homepage,
  10. },
  11. {
  12. path:'*',
  13. component:()=>import('../views/404.vue')
  14. }
  15. ]
  16. })

注意:这个path一定要写在最外面。

2.404.vue页面

这个页面通常我们可以自定义,一般包括跳转某个页面的超链接或者就是定时多长时间进行跳转。

  1. <template>
  2. <div>
  3. <p>
  4. 页面将在<span>{{ time }}</span>秒后自动跳转首页,<br>
  5. 您也可以点击这里跳转<a href="https://www.19jp.com">

二.vue3

为什么要分开说呢?因为在vue3中我们进行如下设置:

  1. {
  2. path:'*',
  3. component:()=>import('../views/404.vue')
  4. }

会产生错误,错误信息:Catch all routes ("*") must now be defined using a param with a custom regexp.,意思就是:现在必须使用与自定义Regexp的参数定义所有路由(“*”)。

那么官方是这么说的:

  1. // plan on directly navigating to the not-found route using its name
  2. { path: '/:pathMatch(.*)*', name: 'not-found', component: NotFound },
  3. // if you omit the last `*`, the `/` character in params will be encoded when resolving or pushing
  4. { path: '/:pathMatch(.*)', name: 'bad-not-found', component: NotFound },

那么我们vue2中的index.js文件中的代码就变成了如下:

  1. ...
  2. export default new Router({
  3. routes: [
  4. ...,
  5. {
  6. path:'/:pathMatch(.*)*',
  7. component:()=>import('../views/404.vue')
  8. }
  9. //或者
  10. {
  11. path:'/:pathMatch(.*)',
  12. component:()=>import('../views/404.vue')
  13. }
  14. ]
  15. })

以上就是Vue2和Vue3中如何设置404界面的详细内容,更多关于Vue2和Vue3中如何设置404界面的资料请关注九品源码其它相关文章!