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

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();
  }
})

你可能感兴趣的:(vue,vuex,js基础)