非法请求显示404页面

用户在访问不存在路由时,会显示404页面,用户可自行切换页面或回到首页

404页面作为一个通用页面,任何非法请求,全部都会跳转到404页面上

###

应用到的技术栈

vue3 -- vue-router -- vite -- less

###

进入正题了

###

这里是需要用到的图片

非法请求显示404页面_第1张图片                               

###

PC端编写

首先在views里创建文件夹404,例如404/index.vue

页面搭建




路由配置
import { createRouter, createWebHistory } from "vue-router";
import Home from "../views/Home.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "login",
      component: () => import("../views/Login.vue"),
    },
    {
      path: "/home",
      name: "home",
      component: Home,
    },
    
    // 关键在这里,这里是需要配置的路由
    {
      path: "/404",
      component: () => import("../views/404/index.vue"),
      name: "404",
    },
    {
      path: "/:pathMatch(.*)",
      // 重定向
      redirect: "/404",
      name: "any",
    },
  ],
});

export default router;

###

APP端编写

app的编写和pc的一样,可以看着写一下

页面搭建




路由配置
import { createRouter, createWebHistory } from "vue-router";
import Home from "../views/Home.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "login",
      component: () => import("../views/Login.vue"),
    },
    {
      path: "/home",
      name: "home",
      component: Home,
    },
    // 配置404页面路由
    {
      path: "/404",
      component: () => import("../views/404/index.vue"),
      name: "404",
    },
    {
      path: "/:pathMatch(.*)",
      redirect: "/404",
      name: "any",
    },
  ],
});

export default router;

你可能感兴趣的:(vue.js,前端,javascript)