uniapp微信小程序头像更新

微信小程序 yekong

最近微信小程序关于用户的头像api做了调整

open-type=“getUserInfo” 在2021年4月13日停用
wx.getUserInfo 在2021年4月28日停用
wx.getUserProfile 在2022年11月8日停用

现在用 open-type=“chooseAvatar”

要求版本 2.24.4以上
头像与昵称是分开
获取到头像路径是临时的

<template>
	<div>
		<!-- @click="chooseImage" -->
		<button class="button" open-type='chooseAvatar' @chooseavatar="chooseImage">
			<slot></slot>
		</button>
		<l-clipper v-if="show" :imageUrl="imageUrl" @success="getImage" @cancel="show = false" />
	</div>
</template>

<script>
	import configs from '@/config/config.js'
	import uploadFile from '@/js_sdk/tencentcloud-plugin-cos/upload-file';
	export default {
		data() {
			return {
				show: false,
				configs,
				imageUrl: '',
			}
		},
		props: {
			name: {
				type: String,
				default () {
					return '';
				}
			}
		},
		onShow() {

		},
		watch: {
			show() {
				this.$emit('getshow', this.show)
			},
		},
		methods: {
			async getImage(e) {
				var that = this;
				that.show = false
				const key = await uploadFile(e.url); // 返回的key即上传到COS的图片文件名(不包含域名部分,一般用来提交给后台接口保存到数据库)
				const url = configs.uploadImg + key; // 返回的url即前面上传到COS的图片的访问地址(包含临时签名)
				that.$emit('getdata', {
					key: key,
					url: url
				})
			},
			chooseImage(e) {
				var that = this;
				console.log(e.detail.avatarUrl)
				that.imageUrl = e.detail.avatarUrl
				that.$nextTick(() => {
					that.show = true
				})
				// that.uploadimg(e.detail.avatarUrl)
				// uni.chooseImage({
				// 	count: 1,
				// 	sizeType: ['compressed'],
				// 	success: res => {
				// 		that.imageUrl = res.tempFilePaths[0]
				// 		that.$nextTick(() => {
				// 			that.show = true
				// 		})
				// 		// that.uploadimg(res.tempFilePaths[0]);
				// 	},
				// 	fail: err => {
				// 		// #ifdef MP
				// 		uni.getSetting({
				// 			success: res => {
				// 				let authStatus = res.authSetting['scope.album'] && res.authSetting[
				// 					'scope.camera'];
				// 				if (!authStatus) {}
				// 			}
				// 		});
				// 		// #endif
				// 	}
				// });
			},
			uploadimg(url) {
				var that = this;
				if (uni.getStorageSync('token')) {
					let a = uni.uploadFile({
						url: configs.uploadPic, // 仅为示例,非真实的接口地址
						filePath: url,
						name: 'pic',
						header: {
							'Authorization': 'Bearer ' + uni.getStorageSync('token')
						},
						success: (res) => {
							that.$emit('getdata', JSON.parse(res.data).data)
							if (JSON.parse(res.data).code == 401) {
								uni.redirectTo({
									url: '/pages/login/login'
								})
							}
						},
						fail: (res) => {
							if (res.code == 401) {
								uni.redirectTo({
									url: '/pages/login/login'
								})
							}
						}
					});
				} else {
					uni.redirectTo({
						url: '/pages/login/login'
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	button {
		border: none;
		background: none;
		padding: 0;
		border: 0;
		margin: 0;
		line-height: 0;
	}

	button::after {
		border: none;
	}
</style>

喜欢