获取用户信息并存储到vuex中

15 篇文章 0 订阅
2 篇文章 0 订阅

在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)
      }

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值