有的业务需要监听热启动,比如,当再次打开小程序时,重新获取用户的实时定位
- 首先需要在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)
}
}
})
})
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。