微信小程序雖然便捷,但是在開發階段,坑還是很多的。以下是我最近寫小程序總結的一些小心得,望參考一二。
1、wx:if條件判斷
當判斷的內容是由多個組件標籤組合的,則需要使用<block/>標籤
<block wx:if="{{true}}"> <!--條件渲染內容--> <view> view1 </view> <view> view2 </view> </block>
2、引入iconfont時,在app.wxss做全局引用,但是這個全局僅侷限於page裏面的頁面,不包括組件,如果組件需要引入iconfont,需要在每個組件的wxss引入
app.wxss:全局引入
@import 'iconfont.wxss';
單個引入
@import '../../../iconfont.wxss';
3、在使用tabbar時,在另一個頁面需要跳轉到tabbar所在頁面,並關閉其他非tabbar頁面,一般使用wx.switchTab去跳轉,但是頁面不會去刷新,
而reLaunch()則是先關閉了所有頁面,再跳轉到指代的頁面,會去刷新
4、在js中,初始化時在data定義的初始值爲對象或者數組時,在接下來的修改data時,會麻煩點。需要把需要修改的變量去賦值給一個變量,在使用this.setData()的時候,需要給這個變量加上中括號,具體寫法如下紅字所示:
data: { circleId: '', data: {}, commentData: {}, isComment: false, isCollect: false, circleid: '', comment: '', curPage: 0, pageSize: 10, commentId: 0, commentDataShow: '展開評論', albumId: '' }, // 二級評論的點贊 loveComment2(e) { console.log(e) let dataset = e.currentTarget.dataset let type = dataset.commenttype let commentId = dataset.commentid let index = dataset.index let index2 = dataset.index2 let isLoveStr = `commentData[${index}].secondComments[${index2}].secondIsLove` let secondCommentCountStr = `commentData[${index}].secondComments[${index2}].secondCommentCount` let secondIsLove = dataset.secondislove let secondCommentCount = dataset.secondcommentcount if (secondIsLove) { comment.cancelLoveComment(commentId, type).then(res => { if (res.status == 'SUCCESS') { this.setData({ [isLoveStr]: 0, [secondCommentCountStr]: secondCommentCount - 1 }) } }) } else { comment.loveComment(commentId, type).then(res => { if (res.status == 'SUCCESS') { this.setData({ [isLoveStr]: 1, [secondCommentCountStr]: secondCommentCount + 1 }) } }) } },
5、將不需要刷新的數據放到onLoad中執行,將不需要刷新的數據放到onShow中執行
6、微信小程序自定義組件pageLifetimes和lifetimes的區別
lifetimes:指的是組件的生命週期,pageLifetimes:指的是組件頁面的生命週期
如果tabbar頁面使用了組件,還想在切換的時候及時刷新頁面,組件初始化放在pageLifetimes中的show中
詳見官方文檔:https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/component.html?search-key=%E6%9E%84%E9%80%A0%E5%99%A8