路由有重定向情况,但是有些页面和场景需要阻止重定向,如何实现
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;
实测有效(本人业务场景:从另外一个项目跳转到本项目的一个页面,不做处理就会跳转后立马刷新到首页)