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