diff --git a/src/store/modules/user.js b/src/store/modules/user.js index 309f03d..8e6fd1f 100644 --- a/src/store/modules/user.js +++ b/src/store/modules/user.js @@ -1,5 +1,5 @@ // import { login, logout, getInfo } from '@/api/user' -// import { getToken, setToken, removeToken } from '@/utils/auth' +import { getToken, setToken, removeToken } from '@/utils/auth' // import { resetRouter } from '@/router' // const getDefaultState = () => { @@ -95,9 +95,36 @@ // actions // } +// 状态 +// 初始化的时候从缓存中读取状态 并赋值到初始化的状态上 +const state = { + // 2. 页面刷新初始化时, 尝试恢复 + token: getToken() +} +// 修改状态 +const mutations = { + // 设置token + setToken(state, data) { // 这里的setToken是user.js里新定义的方法, 不是auth.js里的 + // 这里只是对 vuex 数据的处理 + // 但是没有持久化 + // 持久化的两个步骤 + // 1. 数据发生变化时, 存放起来 + setToken(data) + state.token = data + }, + // 删除缓存 + removeToken(state) { + state.token = null // 删除vuex的token + removeToken() // 先清除 vuex 再清除缓存 vuex和 缓存数据的同步 + } +} +// 执行异步 +const actions = { +} + export default { namespaced: true, - state: {}, - mutations: {}, - actions: {} + state, + mutations, + actions } diff --git a/src/utils/validate.js b/src/utils/validate.js index dd9c2fd..9945354 100644 --- a/src/utils/validate.js +++ b/src/utils/validate.js @@ -19,6 +19,7 @@ export function validUsername(str) { return valid_map.indexOf(str.trim()) >= 0 } +// 手机号码验证 // valid 有效的 // 校验通过返回true export function validMobile(str) { diff --git a/src/views/login/index.vue b/src/views/login/index.vue index 140d68c..d6f829a 100644 --- a/src/views/login/index.vue +++ b/src/views/login/index.vue @@ -126,28 +126,16 @@ export default { this.$refs.password.focus() }) }, - handleLogin() { - // 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 - // } - // }) - - login({ - mobile: '13800000002', - password: '123456' - }).then(res => { - console.log(res.data) - }) + async handleLogin() { + try { + await this.$refs.loginForm.validate() + const res = await login(this.loginForm) + if (!res.data.success) { + this.$store.commit('user/setToken', res.data.data) + } + } catch (error) { + console.log(error) + } } } }