Posted in Javascript onMay 27, 2019
众所周知,vue可以用来开发移动端app,可以使用hbuilder将build好的vue打包成一个移动端app,但是用过之后就会发现,使用cookies或者session保存登录的token,在手机端无法保存,每次打开app依然提示登录。那么我们可以使用localStorage来保存登录信息就可以了,具体代码如下
1、vuex stroe代码
index.js
import Vue from 'vue' import vuex from 'vuex' import { login, logout, getInfo } from '@/api/login' import { getToken, setToken, removeToken, setlocalStorage, getlocalStorage, removelocalStorage } from '@/utils/user' Vue.use(vuex); //state为访问状态对象 数字常量等 const state = { x:5, token: getlocalStorage(), nickname: '', course_id: 0, user_id: 0, group_id: 0, begin_group_num: 0, student_group: 0 }; //访问触发状态mutation是同步的 //actions是异步的 const mutations = { SET_TOKEN: (state, token) => { state.token = token }, SET_NAME: (state, nickname) => { state.nickname = nickname }, }; const actions = { Login({ commit }, userInfo) { const username = userInfo.username.trim() return new Promise((resolve, reject) => { login(username, userInfo.password).then(response => { const data = response.data setlocalStorage(data.token) commit('SET_TOKEN', data.token) resolve() }).catch(error => { console.log() reject(error) }) }) }, GetInfo({ commit }) { return new Promise((resolve, reject) => { getInfo().then(response => { const data = response.data console.log(data) commit('SET_NAME', data.nickname) resolve() }).catch(error => { console.log() }) }) }, // 前端 登出 FedLogOut({ commit }) { return new Promise(resolve => { commit('SET_TOKEN', '') removelocalStorage() resolve() }) } }; //getters 类似于生命周期里面的钩子,getters是在页面刚刚加载完毕之后马上加载,类似于生命周期里面的created const getters = { // 测试getters x: state => state.x + 200, }; export default new vuex.Store({ state, mutations, getters, actions })
2、localStorage 代码
user.js
import Cookies from 'js-cookie' const TokenKey = 'MuseUi-Token' export function getToken() { return Cookies.get(TokenKey) } export function setToken(token) { return Cookies.set(TokenKey, token) } export function removeToken() { return Cookies.remove(TokenKey) } const SessionKey = 'usertoken' export function setlocalStorage(token) { return localStorage.setItem(SessionKey,token) } export function getlocalStorage() { return localStorage.getItem(SessionKey) } export function removelocalStorage() { return localStorage.setItem(SessionKey,null) }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。
vue使用localStorage保存登录信息 适用于移动端、PC端
- Author -
haeasringnar声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@