我是靠谱客的博主 从容钢笔,这篇文章主要介绍使用vuex存储用户信息到localStorage的实例,现在分享给大家,希望可以做个参考。

1、首先需要装vuex

复制代码
1
npm install vuex -d

2、新建store文件夹,新建index.js, 并引入vue、vuex,代码如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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,

复制代码
1
2
3
4
5
6
7
8
import store from './store/index' new Vue({ el: '#app', router, store, // 引入store components: { App }, template: '<App/>' })

4、在登录组件中,如代码所示:

复制代码
1
2
3
4
5
6
this.$message({ message: '登录成功', type: 'success' }) this.$store.commit('$_setStorage', {user: this.loginForm.username}) this.$router.push({name: 'Home'})

5、储存其他状态类信息,方式相同。

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

最后

以上就是从容钢笔最近收集整理的关于使用vuex存储用户信息到localStorage的实例的全部内容,更多相关使用vuex存储用户信息到localStorage内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(151)

评论列表共有 0 条评论

立即
投稿
返回
顶部