0

element ui框架(vuex3使用)

 1 year ago
source link: https://feixiaoxing.blog.csdn.net/article/details/126924226
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

element ui框架(vuex3使用)

【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】

        前面我们使用了sessionStorage实现了登陆状态的保存。但是sessionStorage保存的数据是有限的,如果希望实现vue不同组件之间的数据共享,可以使用vuex来实现。目前和vue2比较match的vuex是vuex3,这一点需要注意下。

1、安装vuex3

npm install vuex@3 --save-dev

2、在main.js中添加vuex

3、创建一个store目录,准备index.js文件



newCodeMoreWhite.png

4、在main.js中加入刚刚创建的store对象

5、在submitForm中增加代码

this.$store.dispatch("asyncUpdateUser", {name:this.form.name});

6、在Main.vue中修改span中的显示方法

<span>{{$store.getters.getUser.name}}</span>

7、测试验证

        在没有添加vuex之前,登录到Main页面之后。如果继续点击/MemberLevel,或者是/MemberList,就会出现用户丢失的情况。现在有了vuex,这种现象不会出现了。

8、继续解决页面刷新后,用户信息丢失的问题

        要解决这个问题,需要有两个地方做出修改,一个是在Main.vue中添加页面刷新回调,保证页面刷新前数据保存到sessionStorage;另外一个就是store的index.js做出修改,主要是state的初始化。

8.1 Main.vue添加回调函数

8.2 修改store/index.js中state的初始化函数

        有了8.1和8.2这两部分,基本就可以解决页面F5刷新后,用户信息丢失的问题。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK