1. 程式人生 > >mpvue小程式踩坑

mpvue小程式踩坑

1. 靜默登入 呼叫wx.login()
2. 請求資料要先登入,有相關許可權才可進行,wx.login()會返回相關token將他們儲存起來,否則報401未授權錯誤
3. promise是用來處理非同步請求的,若為同步方法直接返回相關資料即可,呼叫非同步promise物件的時候,不要在一個函式中呼叫一個函式,而是return一個函式
login () {
      AuthService.wxLogin().then(res => {
        if (res.code === 0) {
          this.userInfo = this.$getStorageSync('userInfo'
) return ShopInfoService.getShop() } }).then(res => { if (res.code === 0) { this.shopInfo = res.data[1] return GoodService.requestGoods({shopId: this.shopInfo.id, pageSize: 1}) } }).then(res => { if (res.code === 0) { this
.product = res.data[0] return this.pushStore() } }) },
4. onload裡面不要寫太多,將其中的方法封裝起來再其中呼叫;不要寫太for迴圈,善用陣列forEach()、Object.values()[將一個物件轉換為陣列]
 dealProducts (res) {
      const result = {}
      res.data.forEach((data) => {
        const catalogId = data.catalogs[0].id
data.url = data.media[0].url data.order = data.media[0].order if (result[catalogId]) { result[catalogId].foods.push(data) } else { result[catalogId] = { foods: [ data ], name: data.catalogs[0].name } } }) return Object.values(result) },
5. 應該設定資料預設值,請求資料需要消耗時間