关于前端:vue3-路由配置-路由匹配到404页面

4次阅读

共计 1054 个字符,预计需要花费 3 分钟才能阅读完成。

对于没有匹配到的路由,咱们通常会匹配到某个固定的页面,如 404 页面,在 vue3 中,咱们通常通过 pathMatch 来设置。如下:

 // 办法一:{path: '/:pathMatch(.*)',

        component: () => import ('../views/notFound.vue')
    },
    // 办法二
    {path: '/:pathMatch(.*)*',

        component: () => import ('../views/notFound.vue')
    },

办法二比办法一前面多了个“*”,他们的区别在于是否解析“/”。
如:当我拜访一个不存在的路由“http://127.0.0.1:5173/#/homef…”时,

办法一

<template>
  <div class=''>404 页面找不到了 </div>
  <!-- path: '/:pathMatch(.*)' -->
  <!-- 输入为:homefdfsd/fesdfsd -->
  <h1>{{$route.params.pathMatch}}</h1> 
</template>

办法二

<template>
  <div class=''>404 页面找不到了 </div>
  <!-- path: '/:pathMatch(.*)*' -->
  <!-- 输入为:["homefdfsd", "fesdfsd"] -->
  <h1>{{$route.params.pathMatch}}</h1>
</template>

残缺代码如下

import {
    createRouter,
    createWebHashHistory
} from 'vue-router'

const routes = [
    { 
        path: "/",
        redirect: '/home'
      },{
        path: '/home',
        component: () => import('../views/home.vue')
    },
    {
        path: '/about',
        component: () => import ('../views/about.vue')
    },
    // 办法一:{path: '/:pathMatch(.*)',

        component: () => import ('../views/notFound.vue')
    },
    // 办法二
    {path: '/:pathMatch(.*)*',

        component: () => import ('../views/notFound.vue')
    },
]
const router = createRouter({
    routes,
    history:createWebHashHistory()})

export default router
正文完
 0