uni.getLocation()不能使用this的原因是。。。


想獲取位置並賦值給變量

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;
                            }
                        });

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM