vue.js路由有很多有趣的东西,咱们在此来大致总结下Vue-Router中到底有哪些方式可以渲染404组件页面
第一种
通过redirect
1 2 3 4 5 6
| routes: [
{
path: '*',
component: undefined
}
] |
第二种
通过redirect - 路由重定向,值得注意的是:当前这个undefined必须是你在上面配置过的地址
1 2 3 4 5 6 7 8 9 10
| routes: [
{
path: '/undefined',
component: undefined
},
{
path: '*',
redirect: 'undefined' //上面配置过,后面才能用
}
] |
当前方式你还能这么写
1 2 3 4 5 6 7 8 9 10
| routes: [
{
path: '/undefined',
component: undefined
},
{
path: '*',
redirect:{path:'/undefined'}
}
] |
第三种
对象通过name别名写法,同样,还是通过上面配置过的路由地址进行跳转
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| routes: [
{
path: '/undefined',
name: 'nofind',
component: undefined,
meta:{
login:true,
title:'undefined'
}
},
{
path: '*',
redirect:{name:'nofind'}
}
] |
第四种
动态设置重定向目标
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| routes: [
{
path: '/undefined',
name: 'nofind',
component: undefined,
meta:{
login:true,
title:'undefined'
}
},
{
path: '*',
redirect:(to) => {
/*console.log(to) //to,目标路由对象,当前访问的目标路由信息
return '/undefined'//重定向到一个上面配置过的路由地址*/
//当然,既然说是动态设置,那么肯定不能向上述那样简简单单return完事,如下:
if(to.path == '/abc'){
return '/home' //如果目标路径是abc,那么我重定向到首页home
}
return '/undefined' //其他正常时候跳转到404
}
}
] |
不仅仅只是上面这些方式,其实我们还有别的方式也可以进行跳转重定向,小伙伴,比如通过钩子函数
第五种
通过全局路由钩子函数去配置
1 2 3 4 5 6 7 8 9 10 11
| // 路由钩子函数
//beforeEach即将要进某个路由时候
router .beforeEach ((to , from , next)=>{
if(to .meta .login ){
next(true) //false时候阻止路由执行,默认是true
// next('/login') 在这里判断到后去跳到登录页面,先要在路由里配置
console .log("当前是个404组件,需要登录访问,其实你还没有登录,不过看你可怜兮兮,我暂时让你旁观!")
}else{
next()
}
}) |
1 2 3 4 5 6 7 8 9
| //afterEach进入组件之后,当然,就没有next了,已经进入了组件
router.afterEach((to, from)=>{
if(to.meta.title){
//当进入了组件后,如果meta里有title就设置title(注意,这个位置document前面需要加上window才能访问)
window.document.title = to.meta.title;
}else{
window.document.title = '世上最完整的vue-router案例'
}
}) |
第六种
通过局部路由钩子函数去配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| routes : [
{
path : '/document',
name : 'document',
components : { //多个组件渲染到一个路由(命名视图技术)
default:document , //默认渲染到router-view没有name的路由
slide :slide
},
beforeEnter (to ,from ,next){
//局部路由钩子函数同样有beforeEnter/afterEnter,to可以监听即将到达的路由信息
console .log("路由钩子函数监听到:进入到document组件")
next(true)
}
}
] |
通过上面这么多的方式,你基本上可以胜任绝大多数vue.js项目路由重定向需求
「梦想一旦被付诸行动,就会变得神圣,如果觉得我的文章对您有用,请帮助本站成长」
共 0 条评论关于"Vue.js项目Vue-Router有多少种路由重定向方式?"
最新评论