微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

uniapp的api中使用this不指向vue实例对象的问题

场景还原:

// 比如在uni.getLocation方法中使用this修改data中的数据,this指向会出错
uni.getLocation({
    type: 'wgs84',
    success: function (res) {
        console.log('当前位置的经度:' + res.longitude);
        console.log('当前位置的纬度:' + res.latitude);
        // 这里的this指向会出错,所以数据也不会修改成功
        this.longitude = res.longitude
        this.latitude = res.latitude
    }
})

此时我们要在外面定义一个that,将this的值赋值给它,使用第三方变量去拿到this

// 将this赋值给that
let that = this
uni.getLocation({
    type: 'wgs84',
    success: function (res) {
        console.log('当前位置的经度:' + res.longitude);
        console.log('当前位置的纬度:' + res.latitude);
        // 这里的that拿到的才是data中的数据
        that .longitude = res.longitude
        that .latitude = res.latitude
    }
})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐