前端路由重定向位置如何阻止

路由有重定向情况,但是有些页面和场景需要阻止重定向,如何实现

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/', // 重定向到home
      name: 'Home',
      component: Home,
    },
    {
      path: '/about',
      name: 'About',
      component: About,
    },
    {
      path: '/default',
      name: 'Default',
      component: DefaultPage,
    },
    {
      path: '*',
      redirect: '/',
    },
  ],
});

如果想直接跳到某些页面,通过beforeEnter实现

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
      // 8888888888
      beforeEnter: (from, to, next) => {
      // pathFg url传的阻止重定向标识,如果为true,取消重定向,防止默认调到首页
      const pathFg = to.query.pathFg
      if (pathFg) {
        // 直接rerun阻止重定向
        console.log('111')
        return
      } else {
        // 其余情况正常重定向
        console.log('222')
        next()
      }
      // 8888888888
    },
    },
    {
      path: '/about',
      name: 'About',
      component: About,
    },
    {
      path: '/default',
      name: 'Default',
      component: DefaultPage,
    },
    {
      path: '*',
      redirect: '/',
    },
  ],
});

上面是对重定向的阻止,也可以设置定向目标(举个栗子)

import Vue from 'vue';
import Router from 'vue-router';
import Home from '@/components/Home.vue';
import About from '@/components/About.vue';
import DefaultPage from '@/components/DefaultPage.vue';

Vue.use(Router);

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
    },
    {
      path: '/about',
      name: 'About',
      component: About,
    },
    {
      path: '/default',
      name: 'Default',
      component: DefaultPage,
    },
    {
      path: '/dynamic/:id',
      name: 'Dynamic',
      beforeEnter: (to, from, next) => {
        const { id } = to.params;
        
        // 根据参数 id 判断重定向位置
        if (id === '1') {
          next({ name: 'Home' });
        } else if (id === '2') {
          next({ name: 'About' });
        } else {
          next({ name: 'Default' });
        }
      },
    },
    {
      path: '*',
      redirect: '/',
    },
  ],
});

export default router;

实测有效(本人业务场景:从另外一个项目跳转到本项目的一个页面,不做处理就会跳转后立马刷新到首页)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值