文章转载自:VUE:vuex 用户登录信息的数据写入与获取
整体思路:
- 前台获取用户数据,向后台发送post请求,验证成功后
- 前台接受数据,改变用户登录状态
- 将登录状态及用户数据写入到state中
- 这样多个页面就可以直接使用
this.$store.getters.getuname
调用state中的用户信息
1.向后台发送请求,若成功返回用户名,密码,使用 this.$store.dispatch(‘setLogin’, true);将数据写入到state中
-
页面:login.vue
-
代码:
this.loginData = await getUserInfo(this.uname,this.pwd);
console.log(this.loginData);
if(this.loginData.res==1){
this.$store.dispatch('setLogin', true);
this.$store.dispatch('setAccount',this.loginData.obj.phone );
2.将数据写到state中
-
页面:action.js
-
代码:
setAccount ({commit}, platform) {
commit('SET_ACCOUNT', platform);
},
3.将数据写到state中
-
页面:mutation.js
-
代码:
SET_ACCOUNT (state, platform) {
state.account = platform;
},
4. 添加获取state中对应数据方法
-
页面:getter.js
-
代码:
getuname: (state) => state.account,
5. 使用this.$store.getters.getuname调取数据
-
页面:login.vue
-
代码:
console.log( this.$store.getters.getuname)