使用vuex存儲用戶信息到localStorage的實(shí)例
更新時(shí)間:2019年11月11日 15:46:21 作者:guoxq~
今天小編就為大家分享一篇使用vuex存儲用戶信息到localStorage的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
1、首先需要裝vuex
npm install vuex -d
2、新建store文件夾,新建index.js, 并引入vue、vuex,代碼如下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const key = 'user'
const store = new Vuex.Store({
state () {
return {
user: null
}
},
getters: {
getStorage: function (state) {
if (!state.user) {
state.user = JSON.parse(localStorage.getItem(key))
}
return state.user
}
},
mutations: {
$_setStorage (state, value) {
state.user = value
localStorage.setItem(key, JSON.stringify(value))
},
$_removeStorage (state) {
state.user = null
localStorage.removeItem(key)
}
}
})
export default store
3、在main.js中引入store,
import store from './store/index'
new Vue({
el: '#app',
router,
store, // 引入store
components: { App },
template: '<App/>'
})
4、在登錄組件中,如代碼所示:
this.$message({
message: '登錄成功',
type: 'success'
})
this.$store.commit('$_setStorage', {user: this.loginForm.username})
this.$router.push({name: 'Home'})
5、儲存其他狀態(tài)類信息,方式相同。
以上這篇使用vuex存儲用戶信息到localStorage的實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關(guān)文章
詳解Vue項(xiàng)目引入CreateJS的方法(親測可用)
CreateJS是基于HTML5開發(fā)的一套模塊化的庫和工具。這篇文章主要介紹了Vue項(xiàng)目引入CreateJS的方法(親測),需要的朋友可以參考下2019-05-05
iView UI FORM 動態(tài)添加表單項(xiàng)校驗(yàn)規(guī)則寫法實(shí)例
這篇文章主要為大家介紹了iView UI FORM 動態(tài)添加表單項(xiàng)校驗(yàn)規(guī)則寫法實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
vue實(shí)現(xiàn)在進(jìn)行增刪改操作后刷新頁面
這篇文章主要介紹了vue實(shí)現(xiàn)在進(jìn)行增刪改操作后刷新頁面,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08

