uniapp如何获取微信昵称
uni.login({
provider: 'weixin',
success: function (loginRes) {
// 登录成功
uni.getUserInfo({
provider: 'weixin',
success: function(info) {
// 获取用户信息成功, info.authResult保存用户信息
}
})
},
fail: function (err) {
// 登录授权失败
// err.code是错误码
}
});
遇到什么问题了吗?
uni.login({
provider: 'weixin',
success: result => {
if (result.code) {
// 获取用户信息
uni.getUserInfo({
provider: 'weixin',
success: res => {
const userInfo = res.userInfo;
console.log(userInfo);
},
fail: res => {
console.log(res);
}
})
}
},
fail: result => {
console.log(result);
}
})
建立云数据库,cloudfunction、新建云函数
在uniCloud–>cloudfunctions–>get_label–>index.js中获取label数据
//get_label-index.js
'use strict';
//获取label数据
const db = uniCloud.database()
exports.main = async (event, comtext) => {
let label = await db.collection('label').get()
// 返回客户端
return {
code:200,
msg:'数据请求',
data:label.data
}
}
首页通过unicloud.callFunction方式调取云函数,找到cloudFunction(云函数)中的get_label下的index.js,然后查找云函数中的 db.collection(‘label’)中的label,读取到数据后通过return返回给客户端,客户端通过promise的回调方式(.then方法)接收,在data中定义数组,用来接收获取的label数组,传递给子组件,最后通过props方法将值传给子组件中,在子组件中完成渲染
// index.vue
// 传递给子组件 子组件通过list接收,父组件通过tabList传递
<tab :list="tabList"></tab>
data(){
return{tabList:[]}
}
//在onLoad()中自动调用,在页面渲染之前
onLoad(){
this.getLabel()
}
methods: {
getLabel() {
uniCloud.callFunction({
name:'get_label'
}).then(res=>{
const {result} = res
this.tabList = result.data
})
}
}
// tab.vue props绑定、v-for渲染
<view v-for="(item,index) in list" :key="index">{{item.name}}</view>
props: {
list:{
type:Array,
default() {
return []
}
}
}
根据参考资料和问题,在uniapp中调用微信API获取用户微信昵称的解决方案如下:
可以使用微信小程序的wx.getUserProfile()接口来获取用户的微信昵称和头像等信息。
在调用该接口之前需要先获取用户的授权,可以使用wx.authorize()接口来进行授权。
在uniapp中调用微信小程序的相关API时,需要使用条件编译来进行不同平台的区分,可参考段落0和段落1中的代码示例。
具体实现流程如下:
onLoad() { uni.getProvider({ service: 'oauth', success: (res) => { if (res.provider.indexOf('weixin') >= 0) { // 判断当前环境是否为微信小程序 this.getWechatUserInfo() } else { // 其他环境下的逻辑 } } }) }
getWechatUserInfo () { wx.authorize({ // 授权获取用户信息 scope: 'scope.userInfo', success: () => { this.getUserProfile() }, fail: (err) => { // 授权失败时的逻辑 } }) }
getUserProfile () { wx.getUserProfile({ desc: '获取用户昵称和头像',// 必须要加desc success: (res) => { this.$set(this, 'userInfo', res.userInfo)// 将获取到的用户信息存入uniapp的data中 }, fail: (err) => { // 获取用户信息失败时的逻辑 } }) }