获取用户信息并存储到vuex中
在pages/index/index.vue中<template><div class="container"><div class="login"><img src="/static/imgs/guide_bg.jpg" alt=""><div class="learn">...
·
在pages/index/index.vue中
<template>
<div class="container">
<div class="login">
<img src="/static/imgs/guide_bg.jpg" alt="">
<div class="learn">
<button open-type="getUserInfo" @getuserinfo="getUserInfo">开始学习</button>
</div>
</div>
</div>
</template>
<script>
export default {
methods:{
getUserInfo(e){
//判断授权成功
if(e.mp.detail.userInfo){
console.log(e.mp.detail.userInfo)
//存储到vuex中
this.$store.dispatch("setIsAuthenticate",true)
this.$store.dispatch("setUser",e.mp.detail.userInfo)
}
}
}
}
</script>
由于微信开发文档提供了获取用户信息的组件,但是也要用到vue,所以点击事件用到
<button open-type="getUserInfo" @getuserinfo="getUserInfo">开始学习</button>
获取用户信息后,将信息存储到vuex,这是微信本身做不到的。
src目录下创建store(actions.js,getters.js,index.js,mutation.js)
在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={
//是否授权
isAuthenticate:false,
user:null
};
export default new Vuex.Store({
state,
getters,
mutations,
actions
})
在getters.js:
export const isAuthenticate=state=>state.isAuthenticate;
export const user=state=>state.user;
在mutations.js:
export const setIsAuthenticate=(state,data)=>{
state.isAuthenticate=data;
};
export const setUser=(state,data)=>{
state.user=data;
};
在actions.js:
export const setIsAuthenticate = ({ commit }, data) => {
commit('setIsAuthenticate', data)
};
export const setUser = ({ commit }, data) => {
commit('setUser', data)
};
然后在main.js中引入:
import Vue from 'vue'
import App from './App'
import store from './store/index'
Vue.config.productionTip = false
Vue.prototype.$store = store
App.mpType = 'app'
const app = new Vue(App)
app.$mount()
在App.vue中存储用户信息:
this.$store.dispatch("setIsAuthenticate",true)
this.$store.dispatch("setUser",e.mp.detail.userInfo)
}
更多推荐
已为社区贡献2条内容
所有评论(0)