微信小程序热启动监听

九饼 -
微信小程序热启动监听

有的业务需要监听热启动,比如,当再次打开小程序时,重新获取用户的实时定位

首先需要在app.js里写个自定义监听器,就叫watch好了,watch对象需要监听该页面data的变化,当data变化,就调用watch方法,代码如下:
  watch: function (watchBack) {
    let obj = this.globalData;
    Object.defineProperty(obj, "appShow", {
      configurable: true,
      enumerable: true,
      set: function (value) {
        watchBack(value);
      },
      get: function () {
        return this.appShow
      }
    })
  },

当然,要在app.js的对应方法里更新appShow

  onShow() {
    this.globalData.appShow = true
  },
  onHide() {
    this.globalData.appShow = false
  }

在需要更新定位的页面生命周期onLoad方法中调用该watch方法
getApp().watch(this.watchBack)
本页面的watchBack方法如下:

  watchBack(appShow) {
 if (appShow) {
   // 一旦热启动,就更新当前位置
   getUserLocationFunc().then(res => {
     this.setData({
       userLocation: res
     })
   })
 }
  }

题外话:这里注意,小程序获得用户当前定位需要一定的时间,虽然很短暂,但同样是异步的,所以getUserLocationFunc方法返回promise对象,该方法是引入的公共方法

const { getUserLocationFunc } = require('../../util/public.js')

代码如下:

export const getUserLocationFunc = () => {
  return new Promise((resolve, reject) => {
    wx.getLocation({
      type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
      success: async (response) => {
        // var speed = response.speed; // 速度,以米/每秒计
        // var accuracy = response.accuracy; // 位置精度
        let userLocation = {
          lng: response.longitude,
          lat: response.latitude
        }

        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            async success() {
              // 用户已经同意小程序使用位置
              resolve(userLocation)
            }
          })
        } else {
          // 已授权,直接获得当前位置
          resolve(userLocation)
        }

      }
      
    })
  })
}
特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

Tags 标签

微信小程序启动界面热加载watch

扩展阅读

加个好友,技术交流

1628738909466805.jpg