随笔-生活工作点滴

获取用户信息并储存到vuex

2019-07-04  本文已影响0人  云景玉东

mpvue开发前准备https://www.jianshu.com/p/8fd3962e34e5
src\pages\index\index.vue

<template> 
    <div class="anniu">
        <button open-type="getUserInfo" @getuserinfo="getUserInfo">
            获取用户信息
        </button>
    </div>
</template>

<script>
export default {
    methods:{
        getUserInfo(e){
            if(e.mp.detail.userInfo){
               // console.log(e.mp.detail.userInfo)
               this.$store.dispatch("setIsAuthenticated", true);
               this.$store.dispatch("setUser", e.mp.detail.userInfo);
            }
        }
    }
}
</script>
<style scoped>
</style>

console.log(e.mp.detail.userInfo)是点击按钮把用户信息打印出来,获取用户信息成功,如图所示


image.png

src下如图创建文件夹及文件


image.png
src\store\index.js
import Vue from 'vue';
import Vuex from 'vuex';
import * as getters from './getters';
import * as mutations from './mutations';
import * as actions from './actions';

Vue.use(Vuex);

const state = {
  isAuthenticated: false,
  user: null,
  openId: '',
  lessonInfo: null
};

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions
});

src\store\actions.js

export const setIsAuthenticated = ({ commit }, data) => {
    commit('setIsAuthenticated', data);
  };
  
  export const setUser = ({ commit }, data) => {
    commit('setUser', data);
  };

src\store\getters.js

export const isAuthenticated = state => state.isAuthenticated;
export const user = state => state.user;
export const openId = state => state.openId;
export const lessonInfo = state => state.lessonInfo;

src\store\mutations.js

export const setIsAuthenticated = (state, data) => {
    state.isAuthenticated = data;
  };
  export const setUser = (state, data) => {
    state.user = data;
  };  

这样用户信息就被储存到vuex
欢迎大神加入群聊:467637093共同进步

上一篇下一篇

猜你喜欢

热点阅读