登录页面搭建完成之后,开始搭建个人中心页面,现在面临登录token的存储问题,我们将采用vuex状态管理+本地存储持久化的方案。因为vuex是响应式的,里面的数据改变会响应到使用的页面,本地存储不能响应数据。
对操作数据本地存储进行封装:
// 获取
export const getItem = key => {
const data = window.localStorage.getItem(key)
try {
return JSON.parse(data)
} catch (error) {
return data
}
}
// 存储
export const setItem = (key, data) => {
if (typeof data === 'object') {
data = JSON.stringify(data)
}
window.localStorage.setItem(key, data)
}
// 删除
export const clearItem = (key) => {
window.localStorage.removeItem(key)
}
在store中进行使用:
import Vue from 'vue'
import Vuex from 'vuex'
import { getItem, setItem } from '@/utils/storage'
Vue.use(Vuex)
const TOKEN_KEY = 'TOUTIAO_KEY'
export default new Vuex.Store({
state: {
// user:JSON.parse(window.localStorage.getItem(TOKEN_KEY))
user: getItem(TOKEN_KEY)
},
getters: {
},
mutations: {
setUser (state, data) {
state.user = data
// window.localStorage.setItem(TOKEN_KEY,JSON.stringify(state.user))
setItem(TOKEN_KEY, state.user)
}
},
actions: {
},
modules: {
}
})
同时,我们发送请求需要添加token值,每次都设置太麻烦,我们需要配置请求拦截器,请求拦截器会在发送请求之前执行,这样就可以自动配置:
import store from '@/store'
// 配置请求拦截器
// 添加请求拦截器
request.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
const user = store.state.user
// console.log(user);
if (user && user.token) {
// console.log(config);
config.headers.Authorization = `Bearer ${user.token}`
}
return config
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error)
})
拦截器使用详情可以查询官网:axios文档