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 );
1
2
3
4
5
2.將數據寫到state中
頁面:action.js
代碼:
setAccount ({commit}, platform) {
commit('SET_ACCOUNT', platform);
},
1
2
3
3.將數據寫到state中
頁面:mutation.js
代碼:
SET_ACCOUNT (state, platform) {
state.account = platform;
},
1
2
3
4. 添加獲取state中對應數據方法
頁面:getter.js
代碼:
getuname: (state) => state.account,
homepage.vue中使用
1
2
5. 使用this.$store.getters.getuname調取數據
頁面:login.vue
代碼:
console.log( this.$store.getters.getuname)