plugins
import {doGet,formPost,appJsonPost} from "@/network/request";
/**
* 利用vue的插件机制
*/
export default {
install(Vue){
//将来在vue组件中,使用this.$doGet使用
Vue.prototype.$doGet = doGet; //get访问
Vue.prototype.$formPost = formPost; //post 表单模式
Vue.prototype.$appJsonPost = appJsonPost; //post json模式
}
}
router
import Vue from 'vue' //引入vue
import VueRouter from 'vue-router' //引入路由
import {getItem} from "@/storage"; //引入本地存储的函数
import {USER_TOKEN_KEY} from "@/config/Constants"; //引入常量
import {Message} from "element-ui"; //引入饿了么控件的提示框
import Nprogress from 'nprogress' // 引入进度条
import 'nprogress/nprogress.css' // 引入进度条样式
//使用,注册路由控件
Vue.use(VueRouter)
//路由变量
const routes = [
{
path: '/', //访问路径
redirect: '/login' //重定向
},
{
path: '/login',
name: 'Login', //路由名称
component: ()=> import('@/views/Login.vue'), //组件,懒加载方式
meta: {
title:'登录' //标题
}
},
{
path: '/',
name: 'Main',
component: ()=> import('@/views/Main.vue'),
//路由子项
children:[
{
path: 'index', //子项路径中,未带斜杠的,需将上级路径自动带入前部,比如此项 路径为 /index
name: 'Index',
component: ()=> import('@/views/Index/Index.vue'),
meta: {
title: '首页'
}
},
{
path: 'student', //此项为 /student
name: 'StudentHome',
component: ()=> import('@/views/Student/StudentHome.vue'),
//子项
children: [
{
path: 'manage', //此项为 /student/manage
name: 'StudentManage',
component: ()=> import('@/views/Student/StudentManage.vue'),
meta: {
title: '学生管理'
}
}
]
},
{
path: 'score', // 此项为 /score
name: 'ScoreHome',
component: ()=> import('@/views/Score/ScoreHome.vue'),
children: [
{
path: 'manage', //此项为 /score/manage
name: 'ScoreManage',
component: ()=> import('@/views/Score/ScoreManage.vue'),
meta: {
title: '成绩管理'
}
},
{
path: 'add', //此项为 /score/add
name: 'AddScore',
component: ()=> import('@/views/Score/AddScore.vue'),
meta: {
title: '添加成绩'
}
},
{
path: 'update', //此项为 /score/update
name: 'UpdateScore',
component: ()=> import('@/views/Score/UpdateScore.vue'),
meta: {
title: '更新成绩'
}
}
]
},
]
},
]
//将变量赋值给 vue 路由配置中
const router = new VueRouter({
routes
})
//访问路径白名单
const IGNORE_URLS = ['/','/login'];
//前置守卫
router.beforeEach((to, from, next) => {
//开启进度条
Nprogress.start();
//要访问的路径,在白名单中,放行
if(IGNORE_URLS.includes(to.path)){
next();
}else {
//获取token
let token = getItem(USER_TOKEN_KEY);
if(token){
//有登录
next();
}else {
//未登录的,提示
Message.error('权限失效,请重新登录');
//路由跳转至登录页
next({path: IGNORE_URLS[0]});
}
}
});
//后置守卫
router.afterEach(((to, from) => {
document.title = to.meta.title;
//关闭进度条
Nprogress.done();
}));
export default router
storeage
export function saveItem(key, value) {
if(typeof value === 'object'){
//如果是对象,需要序列化,保存至本地存储
window.localStorage.setItem(key,JSON.stringify(value));
}else {
//如果是字符串,直接保存
window.localStorage.setItem(key,value);
}
}
export function getItem(key) {
//如果key对应的值不存在,返回null
return window.localStorage.getItem(key);
}
export function clearAll() {
//全部清除本地存储的内容
window.localStorage.clear();
}
export function removeItem(key) {
//清除,单项
window.localStorage.removeItem(key);
}