直接获取个人信息。不通过授权
<open-data type="userAvatarUrl" class="avatar avatar-position"></open-data>
<open-data type="userNickName"></open-data>
这种方式直接写在wxml上就可以,为了与js代码交互 我们需要一套完整的方案
授权方案
第一。只能按钮才可以触发 open-type事件。如果我们想用图片直接触发呢
自定义控件
新建commponents/image-button 目录 -》目录下组件叫index
index.js
// components/image-button/index.js
Component({
/**
* 组件的属性列表
*/
options: {
multipleSlots: true
},
properties: {
openType: {
type: String
}
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
onGetUserInfo(event) {
this.triggerEvent('getuserinfo', event.detail,{})
}
}
})
开启插座 multipleSlots
openType 还叫openType 。保留控件的原始性
onGetUserInfo(event) {
this.triggerEvent('getuserinfo', event.detail,{})
}
获取到的事件。抛出给getuserinfo 方法 这个是自定义的可以随便写 这里我们用了getuserinfo
index.wxml
<!--components/image-button/index.wxml-->
<button bind:getuserinfo="onGetUserInfo" open-type="{{openType}}" plain="{{true}}" class="container">
<slot name="img"></slot>
</button>
这里。bind:getuserinfo是系统的那个事件 不是我们自定义的哦。open Type不用多讲也是系统事件。
plain="{{true}}" 去掉按钮边框
slot 是插座,,相当于预留一个位置。
接着看样式
/* components/image-button/index.wxss */
.container{
padding: 0 !important;
border: none !important
}
!imprtant提升样式的优先级。
这样这个组件完成了
使用:
在需要的页面上面的json文件中引用 我们叫v-button
{
"usingComponents": {
"v-button":"/components/image-button/index",
}
}
wxml
<v-button open-type="getUserInfo" bind:getuserinfo="onGetUserInfo">
<image slot="img" src="/images/my/my.png"></image>
</v-button>
bind:getuserinfo 这个事件不是系统的 是我们刚才自定义的
open type 不必多讲。。
slot就是插座。留下一个位置。然后我们现在就是插头了 替换掉
实际图片
效果
完美的把图片外面包了一层button
onGetUserInfo 就是我们要写的事件了
onGetUserInfo(event) {
const userInfo = event.detail.userInfo;
console.log(userInfo)
},
至此授权就结束了。
复杂一点授权切换图片 没授权之前是上图片 授权之后是微信头像。怎么处理
页面 的wxml中
<v-button wx:if="{{!authorized}}" open-type="getUserInfo" class="avatar-position" bind:getuserinfo="onGetUserInfo">
<image slot="img" class="avatar" src="/images/my/my.png"></image>
</v-button>
<view wx:if="{{authorized}}" class="avatar-container avatar-position">
<image src="{{userInfo.avatarUrl}}" class="avatar"></image>
<text>{{userInfo.nickName}}</text>
</view>
这里我们关注这个点
authorized 这个是自定义用户变量 用来切换布局
js data中
data: {
authorized: false,
},
修改刚才授权之后的方法
onGetUserInfo(event) {
const userInfo = event.detail.userInfo;
if (userInfo) {
this.setData({
userInfo,
authorized: true
})
}
},
下面一些相关的wxss我也贴出来吧
.avatar-position {
position: absolute;
top: 255rpx;
}
.avatar {
width: 120rpx;
height: 120rpx;
overflow: hidden;
border-radius: 50%;
}
.avatar-container {
display: flex;
flex-direction: column;
align-items: center;
}
-----------------------------------------------------单身分割线------------------------------------
下面写分享功能
logo
<v-button class="share-btn" open-type="share">
<image class="share" slot="img" src="/images/icon/share.png"></image>
</v-button>
相关wxss
.share-btn{
margin-top: 28rpx;
margin-left: 10rpx
}
.share{
width: 40rpx;
height: 40rpx;
}
done