登录过程(vuex存储数据)
this.$refs.loginForm.validate(valid => {
if (valid) {
this.loading = true
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: {
token: getToken() || ''
},
mutations: {
doLogin(state, newToken) {
state.token = newToken
setToken(newToken)
}
},
actions: {
async login(context, payload) {
const { 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'
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) {
const { data } = await userLogin(payload)
context.commit('doLogin', data.data)
}
第三步:在mutations中修改state中存储的token数据(token持久化)
mutations: {
doLogin(state, newToken) {
state.token = newToken
setToken(newToken)
}
},
第四步:在state中获取token保证最新
state: {
token: getToken() || ''
},
2.2 给请求头统一添加token
service.interceptors.request.use(config => {
if (store.state.user.token) {
config.headers.Authorization = `Bearer ${store.state.user.token}`
}
return config
}