ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# 微信小程序登录 > 微信小程序登录的用法, 在这里我使用的token验证, 登录成功后存入token 以后每个请求都带token > `this.$http` 这个对象是在`main.js`绑定的`request.js` 替代uni.request 因为有拦截器好处理自动带token请求 > [request.js](request.md) #### Code ```vue <template> <view> <view class="top"> <image class="poster" :src="userInfo.avatar" @tap="toAvatar()"></image> <view class="name">{{userInfo.nick_name}}</view> <button open-type="getUserInfo" lang="zh_CN" @getuserinfo="onLogin">获取用户信息</button> </view> </view> </template> <script> export default { data() { return { userInfo: { avatar: '../../static/images/avatar.png', nick_name: '游客' } } }, onLoad() { this.getUserInfo(); }, onShow() { // 避免缓存问题 this.getUserInfo(); }, methods: { // 查询用户信息接口 getUserInfo() { this.$http.get("api/user/get_info").then(({data})=>{ if (data.code==0) { this.userInfo.avatar = data.data.avatar; this.userInfo.nick_name = data.data.nickname; } else { this.userInfo.avatar = "../../static/images/avatar.png"; this.userInfo.nick_name = "游客"; } }).catch(()=>{ uni.showToast({ title:"查询用户信息失败", icon:"none" }) }) }, // 登录 onLogin(res) { let that = this; // 不同意授权 if (!res.detail.iv) { return false; } // 1.wx获取登录用户code uni.login({ provider: 'weixin', success: function(loginRes) { let code = loginRes.code; // 2.查询用户信息 that.$http.get("api/login/wx_login", {code: code}).then(({data}) => { console.log("userInfo", data); if (data.code===0) { // 老顾客了 that.$userId = data.data.uid; // uid that.$http.config.token = data.data.token; // token that.getUserInfo(); // 查询用户信息 } else if (data.code === 200) { // 首次登录 -- 绑定手机/注册 uni.setStorageSync("wxTempInfo", data.data); uni.navigateTo({ url:"bindPhone/bindPhone" }) } else { uni.showToast({ title:data.msg||"查询失败", icon:"none" }) } }).catch(() => {}) } }); } } } </script> ```