值得記錄的(四)- 小程式開發中遇到的一些要點
最近在做商城小程式的會員中心模組專案。之前除了製作過簡單的翻譯小程式之外幾乎沒有做過小程式開發,開發的過程也是一個學習的過程,記錄一些在開發工程中值得記錄的。
getUserInfo 調整
呼叫前需要 使用者授權 scope.userInfo。
這個 API 在進行修改之後,只能夠通過使用者點選來觸發,因此在一個普通元素(view
或者 image
)上進行 bindtap
事件繫結是不可以呼叫 userinfo
的。至少截止到這篇文章發表之時,凡是介面需要獲取 userinfo
必須用 button
button
讓使用者點選,才能夠獲取到 userinfo
。格式為:
<button class="go_to_member" bindgetuserinfo='goMember' open-type="getUserInfo"> <view class="go_cart_member"> 會員資訊 </view> </button>
wx.login
如果介面的請求需要傳遞 code
。那麼 request
ajax
)要在 wx.login
中巢狀進行。
wx.login({
success (res) {
if (res.code) {
//發起網路請求
wx.request({
url: 'https://test.com/onLogin',
data: { code: res.code // 後端需要的值 } }) } else { console.log('登入失敗!' + res.errMsg) } } })
Token 傳值
app.js
Token
為空,獲取到 Token
之後儲存到全域性 globalData
中。然後在跳轉到下一個頁面,下一個頁面請求介面的 url
地址會加上這個 Token
欄位
// app.js 全域性Data
globalData: {
userInfo: null,
domain_name: 'https://xxx.com', // 線上
Token: '', },
當前頁跳轉,並存儲 app.globalData.Token
。
<>
下一頁介面請求地址帶上 app.globalData.Token
。
showLoading
由於一些頁面模組之間的跳轉並不是單純的本地 page 跳轉,為了讓使用者沒有使用卡頓的直接感覺,另一方面解除使用者的等待焦慮心理,使用 showLoading
告知使用者正在載入。
// 開始呼叫 showLoading
wx.showLoading({
title: '載入中...',
})
// 請求結束後 用 complete 呼叫 hideLoading
wx.request({
url: ..., ..., success: (res) => { }, fail: () => {}, complete: () => { wx.hideLoading() } })
例子
loadingGIF 解決頁面抖動
如果前後頁面是使用 navigator
標籤跳轉,進頁面之後再使用 onLoad
進行請求渲染的情況。可能會造成使用者進入頁面時,發生頁面突然重新整理或者頁面渲染抖動的情況出現。這裡我們可以搭配 wx:if
和 loadingGIF
來實現一個頂部的 loading
旋轉圖示,在載入完成,返回 code === 0
的時候才給使用者看再一次性渲染成功的頁面,消除抖動感。當然這裡如果更加節約資源,可以使用 iconfont
或者 svg
搭配 @keyframe CSS
動畫去代替 loadingGIF
。
<view class="waiting_img" wx:if="{{ code !== 0 }}"> <image src="/pages/img/waiting.gif"></image> </view> <view class="wrapper" wx:if="{{ code === 0 }}"> 頁面內容 </view>
// app.wxss
.waiting_img {
width: 100%;
text-align: center;
}
.waiting_img image {
width: 31px !important;
height: 31px !important;
margin-top: 30rpx; }
小程式生命週期 this 搭橋
在 onLoad
生命週期鉤子裡面進行獲取資料並渲染出現了 Cannot read property 'setData' of null
的報錯。
該報錯是由於小程式生命週期鉤子中 this 改變指向導致的,var that = this
之後將 that
用於 setData()
即可。