Vue-element-template 记住密码
1. 在登录页面添加记住密码按钮
-
新增参数 rememberMe
# resources/src/views/login/index.vue loginForm: { username: 'admin', password: '123456', rememberMe: false },
-
添加复选框
# resources/src/views/login/index.vue <div style="margin-bottom: 20px;"> <el-checkbox v-model="loginForm.rememberMe"> <span style="color: #fff; font-size: 12px;"> 记住我 </span> </el-checkbox> </div>
-
提交参数
# resources/src/views/login/index.vue handleLogin() { ………… 不用改 }
2. 在 user module 里改造login方法
-
获取 rememberMe 参数, 传给 setToken 方法
# resources/src/store/modules/user.js login({ commit }, userInfo) { const { username, password, rememberMe } = userInfo return new Promise((resolve, reject) => { login({ username: username.trim(), password: password }).then(response => { const { data } = response commit('SET_TOKEN', data.token) setToken(data.token, rememberMe) resolve() }).catch(error => { reject(error) }) }) },
-
修改setToken方法, 保存到localStorage
#resources/src/utils/auth.js export function setToken(token, persistent = false) { if (persistent) { Cookies.set(TokenKey, token); return localStorageSetItem(TokenKey, token) } else { return Cookies.set(TokenKey, token) } } export function localStorageSetItem(key, value) { const curTime = new Date().getTime() localStorage.setItem(key, JSON.stringify({data: value, time: curTime})) }
-
修改 getToken 和 removeToken
#resources/src/utils/auth.js const TokenKey = 'AUTH-TOKEN'; const EXP = 30; export function getToken() { let token = Cookies.get(TokenKey) if (!token) { token = localStorageGetItem(TokenKey, EXP) } return token } export function removeToken() { localStorageRemoveItem(TokenKey) return Cookies.remove(TokenKey) } export function localStorageGetItem(key, exp) { const data = localStorage.getItem(key) const dataObj = JSON.parse(data) if (dataObj === null || new Date().getTime() - dataObj.time > exp * 864e+5) { return null } else { return dataObj.data } } export function localStorageRemoveItem(key) { localStorage.removeItem(key) }
3. 测试
➜ Genes-Admin git:(ogenes) ✗ npm run watch
4. 定义相关文案的翻译,修改默认文案
#resources/src/i18n/langs/en/login.js
#resources/src/i18n/langs/zh_CN/login.js
#resources/src/i18n/langs/zh_HK/login.js
之前已经翻译过
export const login = {
……
rememberMe: '記住我',
……
}
#<span style="color: #000; font-size: 12px;"> 记住我 </span>
<span style="color: #000; font-size: 12px;"> {{ $t("loginForm.rememberMe") }} </span>