实现思路:
1.router中给需要登录后才能访问的页面配置meta:{needLogin:true}
2.登录页面,调用登录接口成功后,给cookie中存入用户信息(我这里是存uuid和sessionid相关内容)
3.request.js的接口请求拦截器中,根据接口返回的code值判断用户是否登录或登录是否已失效(我这里是未登录和已失效code==1000),失效的话,将cookie中的用户信息移除
4. main.js中使用router.beforeEach,步骤1设置的需登录才能访问的页面中,通过判断cookie中是否有用户的uuid和sessionid信息,确定用户是否已登录(未登录时uuid信息肯定不存在,但登录失效时uuid是存在的,所以要在步骤3中通过判断code值,清除uuid新增)。当用户未登录时跳转到登录页,并将当前页面的重定向路径带到登录页面地址中
1.router index.js 配置哪些页面需要登录才能访问
2.main.js判断用户是否已登录(我用的cookie存储的用户信息,存储方法在auth.js里。)
import Vue from 'vue'
import * as auth from '@/utils/auth'
//判断是否登录
router.beforeEach(function (to, from, next) {
if (to.meta.needLogin) {
//从cookie中获取用户信息,判断是否已登录
if (auth.getAdminInfo().userUuid) {
next(); //表示已经登录
} else {
//未登录
//next可以传递一个路由对象作为参数 表示需要跳转到的页面
next({
name: "login",
query: {redirect: to.meta.redirect} //登录后再跳回此页面时要做的配置
} else {
//表示不需要登录
next(); //继续往后走
3.auth.js里代码,重点部分标红
import Cookies from 'js-cookie'
const TokenKey = 'Admin-Token'
const rolesName = "adminRoles"
const adminInfo = "adminInfo"
// 存储数据localStorage(数组对象格式)
export function setStorageObj(key,obj) {
var str = JSON.stringify(obj);
return localStorage.setItem(key,str);
//获取数据(数组对象格式)
export function getStorageObj(key) {
return JSON.parse(localStorage.getItem(key));
//存储数据(字符串)
export function setStorage(key,data) {
return localStorage.setItem(key,data);
//获取数据(字符串)
export function getStorage(key) {
return localStorage.getItem(key)
//清除数据(所有格式)
export function removeStorage(key) {
return localStorage.removeItem(key);
//存储token
export function getToken() {
return Cookies.get(TokenKey)
export function setToken(token) {
return Cookies.set(TokenKey, token)
export function removeToken() {
return Cookies.remove(TokenKey)
//存储角色
export function getAdminRoles() {
const roles = Cookies.get(rolesName)
if(roles){
console.log(roles)
return JSON.parse(roles)
return ''
export function setAdminRoles(roles) {
return Cookies.set(rolesName, JSON.stringify(roles))
//获取用户信息
export function getAdminInfo() {
console.log('获取用户信息')
const admin = Cookies.get(adminInfo)
if(admin){
return JSON.parse(admin)
return ''
//存储用户信息
export function setAdminInfo(admin) {
return Cookies.set(adminInfo, JSON.stringify(admin))
//移除用户信息
export function removeAdminInfo() {
return Cookies.remove(adminInfo)
4.login.vue页面
methods: {
//登录
login(formName){
this.$refs[formName].validate((valid) => {
if (valid) {
console.log('登录',this.form)
this.$store.dispatch('user/getUserLogin',this.form).then(() => {
this.$router.push({ path: this.redirect || '/' })
}).catch(() => {
this.loading = false
} else {
console.log('error submit!!');
return false;
5.vuex(调用登录接口成功后,存储用户信息)
6.vuex登出
import axios from 'axios'
import { MessageBox, Message} from 'element-ui'
import store from '@/store'
import ElementUI from 'element-ui'
import QS from 'qs'
import * as auth from '@/utils/auth'
// import router from '@/router'
// const hostUrl = 'http://192.168.0.189:8888'
// create an axios instance
const service = axios.create({
// baseURL: hostUrl,
timeout: 50000 // request timeout
//请求头配置
service.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
// request interceptor
service.interceptors.request.use(
config => {
//给请求头添加内容的话,从这里配置
// if (store.getters.token) {
// config.headers['Authorization'] = getToken()
return config
error => {
console.log(error) // for debug
return Promise.reject(error)
// response interceptor
service.interceptors.response.use(
response => {
//未登录、登录过期code==1000
if(response.data.code == 1000){
store.dispatch('user/logout').then(() => {
location.reload()
//其他错误,根据接口返回数据的规律调整
if(response.data.code != 200 && (response.data.code != 1000)){
ElementUI.Message({
type:'error',
message:response.data.message
return Promise.reject('error')
return Promise.resolve(response.data)
error => {
console.log('error',error);
Message({
message: '服务器内部错误',
type: 'error',
duration: 3 * 1000
return Promise.reject(error)
class http {
static async getPage(url, params){
return service.get(url, { params: params })
static async post(url, params){
return service.post(url, QS.stringify(params))
static async postItem(url, params){
if(!params){
params = {};
// params['userUuid']='9E396DE798B240FA8D2162BFE6AC494C';
// params['sessionId']='16e413064c97466c9bef6d9f9e69c5aa';
// 获取userUuid和sessionId
params['userUuid'] = auth.getAdminInfo().userUuid;
params['sessionId'] = auth.getAdminInfo().sessionId;
return service.post(url, params)
static async postNew(url, params){
return service.post(url, params)
export default http