getLocationMethods() {
const pages = getCurrentPages(); // 获取当前页面栈数组
const firstPage = pages[0]; // 获取首页实例
firstPage.properties.getLocation() //直接引用方法给首页数据重新赋值会不生效
// 修改指针转向再调用
const currentInstance = firstPage.$vm; //更改跳转后this的指向
if (currentInstance && currentInstance.getLocation) {
currentInstance.getLocation(); // 调用首页的方法
}
},
上述代码在app.vue
getLocation() {
uni.getLocation({
type: 'wgs84',
success: (res) => {
console.log('当前位置的经度:' + res.longitude);
console.log('当前位置的纬度:' + res.latitude);
// 根据获取的经纬度信息根据后端api得出具体的区域信息
const longitude = res.longitude
const latitude = res.latitude
// 把定位信息存进缓存
uni.setStorageSync('longitude', longitude);
uni.setStorageSync('latitude', latitude);
getAreaQueryByLogLat({
lat: latitude,
log: longitude
}).then(res => {
this.cityInfo.district.name = res.data.district.name
this.cityInfo.district.id = res.data.district.code
this.cityInfo.city.name = res.data.city.name
this.cityInfo.city.id = res.data.city.code
console.log(this.cityInfo)
})
},
fail(err) {
console.error('获取位置失败:', err);
}
});
uni.setStorageSync('cityInfo', this.cityInfo);
},
上述代码在index.vue
调用后会出现res的数据无法赋值到this.xxx上
使用$set会报找不到$set
然后就分别打印两边的this出来发现果然不一致
更改this的指向最后就好了