The applet obtains the latest user information to log in (fill in the avatar and nickname)

<template>
	<view>
		<view class="top" v-if="!userInfo.avatarUrl">
			<!-- 获取用户昵称input -->
			<input type="nickname" class="weui-input" placeholder="请输入昵称" @blur='getInputValue' />
			<!-- 点击获取用户头像 -->
			<button type="primary" open-type='chooseAvatar' @chooseavatar="getUserInfo">获取用户信息</button>
		</view>
		<view v-else>
			<!-- 展示用户昵称和头像 -->
			<view> {
   
   {userInfo.nickName}}</view>
			<image :src="userInfo.avatarUrl" mode=""></image>
			<button type="primary" @click="outLogin">退出登录</button>
		</view>


	</view>
</template>

<script>
	export default {
		props: {

		},
		data() {
			return {
				userInfo: {
					nickName: '',
					avatarUrl: ''
				}

			};
		},
		methods: {
			// 点击按钮获取用户信息
			getUserInfo(e) {
				// console.log(e.detail);
				this.userInfo.avatarUrl = e.detail.avatarUrl
				// 将获取到的用户信息同步存储到storage中
				uni.setStorageSync("avatarUrl", e.detail.avatarUrl)
				this.login()

			},
			//获取昵称
			getInputValue(e) {
				this.userInfo.nickName = e.detail.value
				uni.setStorageSync("nickName", e.detail.value)
			},
			// 登录
			login() {
				uni.login({
					"provider": "weixin",
					"onlyAuthorize": true, // 微信登录仅请求授权认证
					success: function(event) {
						console.log(event);
						const {
							code
						} = event
						//客户端成功获取授权临时票据(code),向业务服务器发起登录请求。
						uni.request({
							url: 'https://api.weixin.qq.com/sns/jscode2session', //仅为示例,并非真实接口地址。
							data: {
								js_code: event.code,
								secret: '57993283b09d259209867a1b5c49ef1d',
								appid: 'wx8e599842ea889b19'
							},
							success: (res) => {
								console.log(res);
								// //获得token完成登录
								// uni.setStorageSync('token', res.token)
							}
						});
					},
					fail: function(err) {
						// 登录授权失败  
						// err.code是错误码
					}
				})
			},
			// 退出登录
			outLogin() {
				uni.removeStorageSync("avatarUrl")
				uni.removeStorageSync("nickName")
				uni.navigateTo({
					url: "../../pages/index/index"
				})
			}

		},

		onLoad() {
			// 刷新页面保持登录状态
			this.userInfo.avatarUrl = uni.getStorageSync("avatarUrl");
			this.userInfo.nickName = uni.getStorageSync("nickName")
		},
		components: {

		},
	};
</script>

<style scoped>

</style>

Guess you like

Origin blog.csdn.net/qq_46376192/article/details/129276323