vue-router配置

vue项目中vue-router的处理

import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/views/login'
import Error from '@/views/error'
import ModifyPassword from '@/views/modifypassword'
import Resetpsd from '@/views/resetpsd'
import MailConfirm from '@/views/mailconfirm'
import {getCookie} from '../utils/util'
// 或者你可以新建一个方法
Router.prototype.goBack = () => {
    merchantwallet.rountisBack = true
    window.history.go(-1)
}
Vue.use(Router)

const router = new Router({
    mode: 'history',
    base: '/',
    routes: [
        {
            path: '/error',
            name: '找不到该页面',
            component: Error
        },
        {
            path: '/login',
            name: '登录',
            component: Login
        },
        {
            path: '/modifypassword',
            name: '修改密码',
            component: ModifyPassword,
            meta:{ requiresAuth: true }  //需要鉴权
        },
        {
            path: '/resetpsd',
            name: '找回密码',
            component: Resetpsd
        },
        {
            path: '/mailconfirm',
            name: '邮件确认',
            component: MailConfirm
        },
        {
            path: '/...',
            name: '功能页',
            component: ...,
            meta:{ requiresAuth: true }  //需要鉴权
        }
    ]
})

/**
 *  路由拦截
 *  所有需要鉴权的页面,如果存储登录态的cookie不存在就跳登录页
 */
router.beforeEach((to,from,next)=>{
    if(to.matched.some(record=>record.meta.requiresAuth)){   //遍历 $route.matched 来检查路由记录中的 meta 字段
        if(getCookie('session')){
            next()          //进行路由管道中的下一个钩子
        }else{
            next({
                path: '/login',
                query: { redirect : to.fullPath }
            })
        }
    }else{
        next()
    }
})

export default router;

 

posted @ 2019-05-30 16:39  方小川  阅读(3008)  评论(0编辑  收藏  举报