使用vuex存儲(chǔ)用戶信息到localStorage的實(shí)例
更新時(shí)間:2019年11月11日 15:46:21 作者:guoxq~
今天小編就為大家分享一篇使用vuex存儲(chǔ)用戶信息到localStorage的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
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、儲(chǔ)存其他狀態(tài)類信息,方式相同。
以上這篇使用vuex存儲(chǔ)用戶信息到localStorage的實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- 教你在Vue3中使用useStorage輕松實(shí)現(xiàn)localStorage功能
- javascript中l(wèi)ocalStorage本地存儲(chǔ)(新增、刪除、修改)使用詳細(xì)教程
- JavaScript中本地存儲(chǔ)(LocalStorage)和會(huì)話存儲(chǔ)(SessionStorage)的使用
- 如何在JavaScript中使用localStorage詳情
- vue 使用localstorage實(shí)現(xiàn)面包屑的操作
- JavaScript本地儲(chǔ)存:localStorage、sessionStorage、cookie的使用
- Vue3封裝localStorage基本使用示例詳解
相關(guān)文章
詳解Vue項(xiàng)目引入CreateJS的方法(親測(cè)可用)
CreateJS是基于HTML5開發(fā)的一套模塊化的庫和工具。這篇文章主要介紹了Vue項(xiàng)目引入CreateJS的方法(親測(cè)),需要的朋友可以參考下2019-05-05iView UI FORM 動(dòng)態(tài)添加表單項(xiàng)校驗(yàn)規(guī)則寫法實(shí)例
這篇文章主要為大家介紹了iView UI FORM 動(dòng)態(tài)添加表單項(xiàng)校驗(yàn)規(guī)則寫法實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01vue實(shí)現(xiàn)在進(jìn)行增刪改操作后刷新頁面
這篇文章主要介紹了vue實(shí)現(xiàn)在進(jìn)行增刪改操作后刷新頁面,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-08-08