1. 程式人生 > 實用技巧 >小程式開發常用幾個api、生命週期鉤子和注意事項

小程式開發常用幾個api、生命週期鉤子和注意事項

<!--pages/testwxApi.wxml-->
<view>
  <view>測試微信api</view>
  <!-- 如果只是展示使用者頭像暱稱,可以使用 <open-data /> 元件 -->
  <!-- 頭像元件 拿到的是使用者微信頭像 -->
  <open-data type="userAvatarUrl"></open-data>
  <!-- 暱稱元件 拿到的是使用者微信名 -->
  <open-data type="userNickName"></
open-data> <!-- 需要使用 button 來授權登入 canIUse版本相容--> <button wx:if="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">授權登入</button> <view wx:else>請升級微信版本</view> <!--wx.login() 獲取登入憑證(code)。通過憑證進而換取使用者登入態資訊,包括使用者的唯一標識(openid)及本次登入的會話金鑰(session_key)等
--> <button bindtap="wxLogin">微信登入</button> <!-- 小程式微信支付 --> <button bindtap="wxPay">小程式微信支付</button> <!-- 獲取當前的地理位置、速度。當用戶離開小程式後,此介面無法呼叫。開啟高精度定位,介面耗時會增加,可指定 highAccuracyExpireTime 作為超時時間。地圖相關使用的座標格式應為 gcj02 --> <button bindtap="getGPS">獲取當前的地理位置</
button> <!-- 小程式資料儲存在本地快取 --> <button bindtap="wxCache">小程式快取功能</button> </view>
// pages/testwxApi.js
Page({
  /**
   * 頁面的初始資料
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  /**
   * 生命週期函式--監聽頁面載入
   */
  onLoad: function (options) {
    console.log('生命週期回撥—監聽頁面載入', '第一步')
    // "shareAppMessage"表示“傳送給朋友”按鈕,"shareTimeline"表示“分享到朋友圈”按鈕
    // 顯示“分享到朋友圈”按鈕時必須同時顯示“傳送給朋友”按鈕,顯示“傳送給朋友”按鈕時則允許不顯示“分享到朋友圈”按鈕
    // 與之對應的還有 wx.hideShareMenu 隱藏方法
    wx.showShareMenu({
      withShareTicket: true, // 是否使用帶 shareTicket 的轉發
      menus: ['shareAppMessage', 'shareTimeline'],
      success(res) {
        console.log(res)
      },
      fail(e) {
        console.log(e)
      }
    })
    // 獲取系統資訊--- 還可以做高度自適應(res.windowHeight // 可視高度)
    wx.getSystemInfo({
      success(res) {
        console.log(res, '系統資訊')
      }
    })
    // 檢視是否授權
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已經授權,可以直接呼叫 getUserInfo 獲取頭像暱稱
          wx.getUserInfo({
            success: function (res) {
              console.log(res.userInfo, '微信使用者資訊')
            }
          })
        }
      }
    })
  },
  // 授權登入
  bindGetUserInfo(e) {
    console.log(e, 'e')
    console.log(e.detail.userInfo)
  },
  // 微信登入 一般app.js處理
  wxLogin() {
    // wx.login() 傳送 res.code 到後臺換取 openId, sessionKey, unionId
    wx.login({
      success(res) {
        console.log(res, 'res微信登入')
        if (res.code) {
          //發起網路請求
        } else {
          console.log('登入失敗!' + res.errMsg)
        }
      }
    })
  },
  // 發起微信支付
  wxPay() {
    wx.requestPayment({
      timeStamp: '', // 必填
      nonceStr: '', // 必填
      package: '', // 必填
      signType: 'MD5', // 非必填
      paySign: '', // 必填
      success(res) {

      },
      fail(res) {

      }
    })
  },
  // 獲取地理位置 需要再 app.json裡面配置 permission 欄位如: "scope.userLocation": {"desc": "你的位置資訊將用於小程式位置介面的效果展示" }
  // wgs84 返回 gps 座標,gcj02 返回可用於 wx.openLocation 的座標  對應的開啟地圖選擇位置 wx.chooseLocation()
  getGPS() {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        console.log(res, '獲取地理位置經緯度')
      },
      fail: (error) => {
        console.log(error, 'error如果拒絕授權繼續引導授權')
        wx.showModal({
          content: '請授權使用者地理位置',
          confirmColor: "#ff6700",
          success(res) {
            if (res.confirm) {
              wx.openSetting({
                success(res) {
                  // console.log(res.authSetting)
                  res.authSetting = {
                    "scope.userInfo": true,
                    "scope.userLocation": true
                  }
                }
              })
            }
          }
        })
      }
    })
  },
  // 小程式快取效果方法 存wx.setStorage(Object object) 取wx.getStorage(Object object) 刪wx.removeStorage(Object object) 清除所有 wx.clearStorage(Object object)
  // 小程式快取效果方法(同步版本) 存wx.setStorageSync(Object object) 取wx.getStorageSync(Object object) 刪wx.removeStorageSync(Object object) 清除所有 wx.clearStorageSync(Object object)
  wxCache(){
    wx.setStorageSync('name', 'bob') // 也可以用物件鍵值對的形式存取
    console.log(wx.getStorageSync('name'),'取出快取的值看看')
  },
  /**
   * 生命週期函式--監聽頁面顯示
   */
  onShow: function () {
    console.log('生命週期回撥—監聽頁面顯示', '第二步')
  },
  /**
   * 生命週期函式--監聽頁面初次渲染完成
   */
  onReady: function () {
    console.log('生命週期回撥—監聽頁面初次渲染完成', '第三步')
  },
  /**
   * 生命週期函式--監聽頁面隱藏
   */
  onHide: function () {

  },
  /**
   * 生命週期函式--監聽頁面解除安裝
   */
  onUnload: function () {

  },
  /**
   * 頁面相關事件處理函式--監聽使用者下拉動作
   */
  onPullDownRefresh: function () {

  },
  /**
   * 頁面上拉觸底事件的處理函式
   */
  onReachBottom: function () {

  },
  /**
   * 使用者點選右上角分享  監聽使用者點選頁面內轉發按鈕(button 元件 open-type="share")或右上角選單“轉發”按鈕的行為,並自定義轉發內容。
    注意:只有定義了此事件處理函式,右上角選單才會顯示“轉發”按鈕
   */
  onShareAppMessage: function (res) {
    console.log('點選了右上角分享')
    if (res.from === 'button') {
      // 來自頁面內轉發按鈕
      console.log(res.target)
    }
    return {
      title: '自定義轉發標題----預設當前小程式名稱',
      path: '/page/testwxApi?id=11, 轉發路徑, 預設是 當前頁面 path ,必須是以 / 開頭的完整路徑',
      imageUrl: '自定義圖片路徑,可以是本地檔案路徑、程式碼包檔案路徑或者網路圖片路徑。支援PNG及JPG。顯示圖片長寬比是 5:4, 預設是 使用預設截圖'
    }
  },
  // 監聽右上角選單“分享到朋友圈”按鈕的行為,並自定義發享內容。 注意:只有定義了此事件處理函式,右上角選單才會顯示“分享到朋友圈”按鈕
  onShareTimeline: function (res) {
    console.log(res, '分享朋友圈')
    // 必須要寫return的內容目前的版本分享朋友圈的才不會變灰色
    return {
      title: '自定義標題--預設當前小程式名稱',
      query: '自定義頁面路徑中攜帶的引數如id="11"---預設當前頁面路徑攜帶的引數',
      imageUrl: '自定義圖片路徑,可以是本地檔案或者網路圖片。支援 PNG 及 JPG,顯示圖片長寬比是 1:1,預設使用小程式 Logo'
    }
  },
  // 監聽使用者點選右上角選單“收藏”按鈕的行為,並自定義收藏內容
  onAddToFavorites(res) {
    // webview 頁面返回 webviewUrl
    console.log('WebviewUrl: ', res.webviewUrl)
    return {
      title: '自定義標題--預設-頁面標題或賬號名稱',
      imageUrl: 'http://demo.png 自定義圖片,顯示圖片長寬比為 1:1 預設-頁面截圖',
      query: 'name=xxx&age=xxx  自定義query欄位---預設-當前頁面的query',
    }
  }
})

親測有效,原創總結,轉載請註明出處!