网络编程 
首页 > 网络编程 > 浏览文章

使用vuex存储用户信息到localStorage的实例

(编辑:jimmy 日期: 2025/6/19 浏览:3 次 )

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、储存其他状态类信息,方式相同。

以上这篇使用vuex存储用户信息到localStorage的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:vue 实现通过vuex 存储值 在不同界面使用
下一篇:JS中比较两个Object数组是否相等方法实例
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。