vue-router配置404的方法

使用 notFound 路由配置
Vue Router 4 及更高版本提供了一个 notFound 选项,你可以在创建路由器实例时使用它来指定一个 404 页面:

import { createRouter, createWebHistory } from 'vue-router';
import Home from './views/Home.vue';
import NotFound from './views/NotFound.vue';

const routes = [
  // ... 其他路由配置
];

const router = createRouter({
  history: createWebHistory(),
  routes: [
    ...routes,
    {
      path: '/:catchAll(.*)', // 使用 catchAll 捕获所有未匹配的路由
      name: 'NotFound',
      component: NotFound
    }
  ],
  notFound: {
    component: NotFound // 指定 404 页面组件
  }
});

export default router;

使用重定向

在 Vue Router 3 或者不支持 notFound 选项的版本中,你可以使用重定向来实现类似的效果:

import Vue from 'vue';
import Router from 'vue-router';
import Home from './components/Home.vue';
import NotFound from './components/NotFound.vue';

Vue.use(Router);

const router = new Router({
  mode: 'history',
  routes: [
    { path: '/', component: Home },
    // ... 其他路由配置
    { path: '*', redirect: '/404' } // 捕获所有未匹配的路由并重定向到 404 页面
  ]
});

router.afterEach((to, from) => {
  if (to.path.startsWith('/404') && !to.matched.length) {
    // 显示 404 页面
  }
});

export default router;

监听路由变化
监听路由变化,并在没有匹配的路由时显示 404 页面:在路由守卫中检查当前的路由是否有匹配的组件,如果没有,就重定向到 404 页面。

router.beforeEach((to, from, next) => {
  if (to.matched.length === 0) {
    // 没有匹配的路由,重定向到 404 页面
    to.path = '/404';
  }
  next();
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值