vue路由登录拦截

vue路由

  • vue路由文件的基本格式
import Vue from 'vue';
import Router from 'vue-router';
import HomePage from './views/Home/HomePage.vue'; // 正常引入组件
const HomePage = () => import('./views/Home/HomePage.vue'); // 以懒加载的方式引入组件
Vue.use(Router);

--------------------------------
const router = new Router({
	// mode: 'history',  // 默认为hash值模式,设置mode为history模式
	routes:[
	{ path:'路由地址',component: '组件名',name: '路由别名' },
	{ path:'/',component: HomePage,name: 'homepage' },
	]
})
--------------------------------
export default router;
  • 动态路由
const router = new Router({
	routes:[
	{ path:'/homepage/:id',component: HomePage,name: 'homepage' },
	{ path:'/homepage/:id/user/:username',component: HomePage,name: 'homepage' },
	]
})

// 访问/homepage/223,如何取值this.$route.params-----{id:223}
// 访问/homepage/223/user/mayun,如何取值this.$route.params-----{id:223,username:mayun}
  • 嵌套路由
const router = new Router({
	routes:[
	{ path:'/homepage',component: HomePage,name: 'homepage',children:[
	{path: '/one',component: One},
	{path: '/two',component: Two},
	{path: '/three',component: Three},
	] },
	]
})
  • 路由跳转&&重定向
// 重定向
const router = new Router({
	routes:[
	{ path:'/homepage',component: HomePage,name: 'homepage',children:[
	{path: '/one',component: One},
	{path: '/two', redirect: to => { return '/one' }}, // 重定向到/one路由
	{path: '/three',component: Three},
	] },
	]
})
// 路由跳转
// '/user/:userId'
router.push({ name: 'user', params: { userId: 123 }}) // 路由显示为'/user/123'
router.replace({path: '/user',params: { userId: 123 }}) // 替换浏览器历史记录中最近的一条为当前跳转的路由
  • 路由守卫
router.beforeEach((to,from,next) => {
	// to: 即将要进入的路由对象
	// from: 即将要离开的路由对象
	// next():是一个函数,在路由拦截中一定要注意调用next()进入下一个步骤,
	// next()- 进入下一个钩子函数,next(false) - 中断当前路由导航,next({path: '/luyou',replace: true})||next({path: '/luyou'}) - 中断当前导航,跳转至下一个路由地址
})
  • 路由导航守卫实现登录拦截
import Vue from 'vue';
import Router from 'vue-router';
const router = new Router ({
  routes: [
    {
      path: '/foo',
      component: Foo,
      children: [
        {
          path: 'bar',
          component: Bar,
          meta: { requiresAuth: true , title: '导航页面1'} // 需要登录
        },
        {
          path: 'bar1',
          component: Bar1,
          meta: { requiresAuth: false , title: '导航页面2'} // 无需登录
        },
        {
          path: 'bar2',
          component: Bar2,
          meta: { requiresAuth: true , title: '导航页面2'} // 需要登录
        }
      ]
    }
  ]
})
router.beforeEach((to, from, next) => {
if (to.meta.title) {
    //判断是否有标题
    document.title = to.meta.title;
  }
// 通过requiresAuth判断当前路由导航是否需要登录
  if (to.matched.some(record => record.meta.requiresAuth)) {
  // 若需要登录访问,检查是否为登录状态
    if (!auth.loggedIn()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next() // 确保一定要调用 next()
  }
})

export default router;

你可能感兴趣的:(vue)