您好,登錄后才能下訂單哦!
眾所周知,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) }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。