背景
不得不提一句:微信小程序的:獲取用戶信息的機制改了(早就改了)。或許是不想讓開發者對用戶“隨意”造成困擾——畢竟有的用戶上來只是爲了“逛一圈”。於是增加了“只有觸發button才能彈窗”的功能。
新版-微信授權機制
<button open-type="getUserInfo" bindgetuserinfo="getUserInfo">授權</button>
//js
onLoad(options){
this.userAuthorized();
},
getUserInfo(event){
const userInfo=event.detail.userInfo;
this.setData({
userInfo:userInfo
})
},
authorized(){
wx.getSetting(){
success:data=>{
if(data.authSetting["scope.userInfo"]){
wx.getUserInfo({
success:data=>{
this.setData({
userInfo:data.userInfo
})
}
})
}
}
}
}
那麼,從老版小程序一路跟進的用戶就該問了:有了open-type爲什麼還要有getUserInfo呢?
要知道,open-type只是爲了獲取用戶信息,這一點上<button>
和原先的<open-type></open-type>
沒有什麼區別,但是!其實獲取完用戶信息,最重要的其實是“ 登錄 ”,這一步就涉及到和服務器的交互了。
登錄操作在服務器端是有一套非常完整的邏輯的,並不像我們所想的那麼簡單,這一點以後再說。
當然,上面的代碼只是闡述一下新版微信小程序改進的地方,下面的纔是重點:
自定義button組件實現用戶授權登錄
爲什麼要用“組件”? —— 方便複用!
我們在於主文件夾同級建立img-button文件夾,作爲button組件的地方。
img-button.wxml
<button bind:getuserinfo="onGetUserInfo"
open-type="{{openType}}" plain="{{true}}" class="container">
<slot name="img"></slot>
</button>
這裏的bind後面必須跟userinfo,這是button組件的API。
img-button.js
Component({
// “備註項”——啓用“插槽”
options:{
multipleSlot:true
},
prototies:{
openType:{
type:String
}
},
methods:{
onGetUserInfo(event){
this.triggerEvent('getUserinfo',event.detail,{})
}
}
})
組件都有一項“必備屬性”——prototies。(就如同vue中的props——接收數據,規範格式)
接收誰的數據? —— 主wxml中傳來的數據!
既然有接收,就有傳出。不然要組件幹嘛。
對!在methods裏面,組件“告訴”調用它的元素——用getUserInfo定義事件,給你傳一個值event.detail
(這個“getUserInfo”將作爲主頁面bind的事件——這裏機制其實和vue中的“$emit”->子組件向父組件傳值,是一樣的)
這樣“一來一往”,自定義組件內部和外面調用文件就能“互相訪問”了。
我們在主文件的json文件裏添加“對自定義組件文件的訪問”:
main.json
"usingComponents":{
...
"v-button":"../img-button/img-button"
}
main.wxml
<v-button wx:if="{{!authorized}}" open-type="getUserInfo" class="..."
bind:getUserinfo="onGetUserInfo">
<image slot="img" class="..." src="圖片路徑" />
</v-button>
<view wx:if="{{authorized}}" class="...">
<image src="{{userInfo.avatarUrl}}" class="..." />
<text>{{userInfo.nickName}}</text>
</view>
這裏還真有一點需要注意的:調用組件時的bind的事件名就是自定義組件內部傳出來的值!(而且必須是)(這一點和上面button組件裏面不同)
main.js
data:{
authorized:false,
userInfo:null
},
onLoad(options){
this.userAuthorized();
},
onGetUserInfo(event){
const userInfo=event.detail.userInfo; //取出組件內部傳出來的值
if(userInfo){
this.setData({
userInfo,
authorized:true
})
}
},
userAuthorized(){
wx.getSetting({
success:data=>{
if(data.authSetting['scope.userInfo']){
wx.getUserInfo({
success:data=>{
this.setData({
authorized:true,
userInfo:data.userInfo
})
}
})
}else{
wx.showToast({
title:'抱歉!請檢查微信',
icon:'none',
duration:1200
})
}
}
})
}