欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vue项目中的三种路由的方式以及路由守卫

程序员文章站 2022-03-25 16:50:36
...

1:这是最常见一种 route的方式

import home from "./home.vue";
import about from "./about.vue";
export default new Router({
  routes: [
		{path: '/home ',name: 'home ',component: home ,meta: {title: 'home',requireAuth:true}},
		{path: '/about ',name: 'about ',component: about ,meta: {title: '关于',requireAuth:true}},
	]
})

2:路由的懒加载方式

const login = r => require.ensure([], () => r(require('@/views/auth/login')), 'login'); //登录
const register = r => require.ensure([], () => r(require('@/views/auth/register')), 'register'); //注册
export default new Router({
  routes: [
		{path: '/home ',name: 'home ',component: home ,meta: {title: 'home',requireAuth:true}},
		{path: '/about ',name: 'about ',component: about ,meta: {title: '关于',requireAuth:true}},
  ]
})

3:

export default new Router({
  routes: [
		 {
	      path:'/transfer/:id',
	      name:'transfer',
	      component:()=>import('@/components/riches/transfer'),  //划转
	      meta:{requireAuth:true}
	    },
  ]
}}

在main.js中

router.beforeEach((to,from,next)=>{
   window.document.title=to.meta.title;
  if(to.meta.requireAuth == true){  //需要登录权限进入的路由
    if(!localStorage.getItem('token')){  //取不到登录信息
       return next({name:'login'})
    }else{  //取得到登录信息,进行下一步
      return next();
    }
  }else{  //不需要登录权限
    return next();
  }
})