文章目錄
微信小程序底部彈出層組件與slot插槽實現了底部彈出層效果,現在將底部彈出層應用於用戶授權。
具體的頁面效果如下:
彈出層bottom-modal組件
修改彈出層bottom-modal組件中slot具名插槽
授權login組件
新建login組件
添加login組件,在login組件中會使用彈出層bottom-modal組件。
引入彈出層bottom-modal組件
首先在login.json中引入彈出層bottom-modal組件
{
"component": true,
"usingComponents": {
"x-bottom-modal": "/components/bottom-modal/bottom-modal"
}
}
在login.wxml中使用彈出層bottom-modal組件,並使用modal-content插槽slot
<x-bottom-modal modalShow="{{modalShow}}">
<view slot="modal-content">
<button class="login"
open-type="getUserInfo"
bindgetuserinfo="onGotUserInfo"
>獲取微信授權信息</button>
</view>
</x-bottom-modal>
button的bindgetuserinfo屬性
open-type 和 bindgetuserinfo 請參考:button
具體說明如下:
用戶授權
login.js
// components/login/login.js
Component({
properties: {
modalShow: Boolean
},
data: {
},
methods: {
onGotUserInfo(event) {
console.log(event)
const userInfo = event.detail.userInfo
// 允許授權
if (userInfo) {
this.setData({
modalShow: false
})
this.triggerEvent('loginsuccess', userInfo)
} else {
this.triggerEvent('loginfail')
}
}
}
})
點擊獲取微信授權信息按鈕,彈出微信授權彈窗
點擊拒絕輸出如下日誌:
點擊允許輸出如下日誌,可以看到授權後輸出了用戶相關的信息。
使用授權login組件
引入login組件
{
"usingComponents": {
"x-search": "/components/search/search",
"x-login": "/components/login/login"
}
}
使用login組件
<x-login modalShow="{{modalShow}}" bind:loginsuccess="onLoginSuccess" bind:loginfail="onLoginFail">
</x-login>
點擊發布按鈕操作
整個過程最開始就是點擊發布按鈕,點擊發布按鈕需要先判斷用戶是否已經授權過,如果已經授權我們自己獲取用戶信息;如果沒有授權過,我們才需要去授權頁面進行操作。代碼如下:
// pages/blog2/blog2.js
Page({
data: {
// 控制底部彈出層是否顯示
modalShow: false,
},
// 發佈功能
onPublish() {
// 判斷用戶是否授權
wx.getSetting({
success: (res) => {
console.log(res)
if (res.authSetting['scope.userInfo']) {
wx.getUserInfo({
success: (res) => {
// console.log(res)
this.onLoginSuccess({
detail: res.userInfo
})
}
})
} else {
this.setData({
modalShow: true,
})
}
}
})
},
onLoginSuccess(event) {
console.log(event)
const detail = event.detail
wx.navigateTo({
url: `../blog-edit/blog-edit?nickName=${detail.nickName}&avatarUrl=${detail.avatarUrl}`,
})
},
onLoginFail() {
wx.showModal({
title: '授權用戶才能發佈',
content: '',
})
},
onLoad: function(options) {
},
})
清除授權數據
如果授權後想清除授權數據,只需選擇 “清除授權數據”即可。