wxGetUserInfo
获取微信用户信息 Helper,使用「头像昵称填写能力」,仅支持微信小程序端。
前置依赖
依赖参数
| 参数名 | 类型 | 说明 |
|---|---|---|
deps.ref | <T>(value: T) => Ref<T> | Vue ref 函数(从 'vue' 导入) |
deps.log | Console['log'] | 日志输出 |
deps.uploadFile | UniApp['uploadFile'] | 上传文件 API(用于上传头像) |
环境要求
- 微信小程序: 仅支持微信小程序端
- Vue环境: 需要 Vue 3 Composition API
函数签名
typescript
function wxGetUserInfoHelper(
deps: GetUserInfoHelperDeps
): {
userInfo: Ref<Partial<UserInfoResult['userInfo']>>
handleChooseAvatar: (event: { detail: { avatarUrl: string } }) => string
handleNicknameInput: (event: { detail: { value: string } }) => string
}
function wxUploadAvatar(
filePath: string,
uploadUrl: string,
deps: UploadAvatarDeps
): Promise<string>
interface GetUserInfoHelperDeps {
ref: <T>(value: T) => Ref<T>
log: Console['log']
}
interface UploadAvatarDeps {
uploadFile: UniApp['uploadFile']
error: Console['error']
}参数
wxGetUserInfoHelper
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
deps | GetUserInfoHelperDeps | 是 | 依赖注入对象 |
wxUploadAvatar
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
filePath | string | 是 | 本地临时文件路径 |
uploadUrl | string | 是 | 服务器上传接口地址 |
deps | UploadAvatarDeps | 是 | 依赖注入对象 |
返回值
wxGetUserInfoHelper
| 类型 | 说明 |
|---|---|
{ userInfo, handleChooseAvatar, handleNicknameInput } | 返回用户信息响应式对象和事件处理函数 |
wxUploadAvatar
| 类型 | 说明 |
|---|---|
Promise<string> | Promise,成功时返回上传后的URL |
工作原理
- 创建响应式对象:使用 Vue ref 创建用户信息响应式对象
- 头像选择:通过
<button open-type="chooseAvatar">触发,获取本地临时路径 - 昵称输入:通过
<input type="nickname">获取用户输入的昵称 - 头像上传:将本地临时路径上传到服务器,获取永久URL
重要提示:
- 自2022年10月25日后,
wx.getUserProfile接口已被收回 - 现在需要使用「头像昵称填写能力」获取用户头像和昵称
chooseAvatar获取的是本地临时路径,需要上传到服务器获取永久链接
使用示例:
vue
<template>
<button open-type="chooseAvatar" @chooseavatar="handleChooseAvatar">
选择头像
</button>
<input type="nickname" @input="handleNicknameInput" />
</template>
<script setup>
import { wxGetUserInfoHelper } from 'zcw-shared/functions/uniapp/user-info/wxGetUserInfo'
import { ref } from 'vue'
const { userInfo, handleChooseAvatar, handleNicknameInput } = wxGetUserInfoHelper({
ref,
log: console.log
})
</script>