想獲取位置並賦值給變量
uni.getLocation({ type: 'wgs84', success: (res)=> { console.log('當前位置的經度:' + res.longitude); console.log('當前位置的緯度:' + res.latitude); this.longitude = res.longitude; this.latitude = res.latitude; } });
報錯:VM487 WAService.js:2 TypeError: Cannot set property 'longitude' of undefined
原因:uni.getLocation 是異步函數 不應該在uni.getLocation中 用this 操作data里的函數,應該重新映射一個this變量
解決方法:
#在外面把this賦值給變量that,再在函數里面使用that var that =this uni.getLocation({ type: 'wgs84', success: (res)=> { console.log('當前位置的經度:' + res.longitude); console.log('當前位置的緯度:' + res.latitude); that .longitude = res.longitude; that .latitude = res.latitude; } });