登录过程(vuex存储数据)
this.$refs.loginForm.validate(valid => {if (valid) {//按钮动画加载,禁用 this.loading = true// 调用vuex的action发送登录请求this.$store.dispatch('user/login', this.loginForm).then(() => {this.$router.push({ path: this.redirect || '/' })this.loading = false}).catch(() => {this.loading = false})} else {console.log('error submit!!')return false}})
vuex中:store/modules/user.js 注意要在store/index.js中导入模块并在modules中添加user
import { userLogin } from '@/api/user'
import { getToken, setToken } from '@/utils/auth'
export default {namespaced: true,state: {//取tokentoken: getToken() || ''},mutations: {doLogin(state, newToken) {//更新token state.token = newToken//存tokensetToken(newToken)}},actions: {async login(context, payload) {//发送请求获取tokenconst { data } = await userLogin(payload)console.log(data.data)context.commit('doLogin', data.data)}}
}
引入的文件 1.登录接口 (此处不写) : @/api/user 2.在cookies中存取token接口 : @/utils/auth
import Cookies from 'js-cookie' //封装的cookies ,也可用本地存储localStorage,此处用cookie存储
const TokenKey = 'vue_admin_template_token'export function getToken() {return Cookies.get(TokenKey)
}export function setToken(token) {Cookies.set(TokenKey, token)
}export function removeToken() {Cookies.remove(TokenKey)
}
2.1 存token详细步骤:
第一步:使用 dispatch 调用vuex中的action
this.$store.dispatch('user/login', this.loginForm)//执行成功后的操作.then(() => {//跳转到首页this.$router.push({ path: this.redirect || '/' })//关闭按钮动画this.loading = false})//执行失败后的操作.catch(() => {this.loading = false})} else {console.log('error submit!!')return false}
第二步:在vuex中的action发送ajax请求获取token,commit到mutation中修改state数据
actions: {async login(context, payload) {//发送请求获取tokenconst { data } = await userLogin(payload)context.commit('doLogin', data.data)}
第三步:在mutations中修改state中存储的token数据(token持久化)
mutations: {doLogin(state, newToken) {//更新token state.token = newToken//存token,做持久化setToken(newToken)}},
第四步:在state中获取token保证最新
state: {//取tokentoken: getToken() || ''},
2.2 给请求头统一添加token
service.interceptors.request.use(config => {// 如果有token,统一添加tokenif (store.state.user.token) {config.headers.Authorization = `Bearer ${store.state.user.token}`}return config
}