首页 > 解决方案 > vuejs没有从箭头函数设置数据属性

问题描述

我在这里发生了一件奇怪的事情:

我在 vue 中有这个数据属性

    data() {
        return {
            currentLat: 'intial Lat',
            currentLong: 'intial Long',
        };
    },
    mounted() {
        this.getCurrentLocation();
    },
    methods: {
        getCurrentLocation() {
            navigator.geolocation.getCurrentPosition((position) => {
                this.currentLat = position.coords.latitude;
                this.currentLong = position.coords.longitude;.

                console.log(this.currentLat); this prints 41.2111

            });
            console.log(this.currentLat); this prints 'intial Lat'
        },
    },

在此处输入图像描述

this.currentLat 未在挂载中设置

我不明白这里发生了什么!太奇怪了!

标签: vue.jsvuejs2

解决方案


下面是一个转换为 Promise 并使用 async/await 的示例:

async getCurrentLocation() {
    const position = await new Promise(resolve => {
        navigator.geolocation.getCurrentPosition(position => resolve(position))
    });

    this.currentLat = position.coords.latitude;
    this.currentLong = position.coords.longitude;

    console.log(this.currentLat); // shouldn't print initial value
},

推荐阅读