【问题标题】:vuejs not setting data property from arrow functionvuejs没有从箭头函数设置数据属性
【发布时间】:2020-11-27 21:09:34
【问题描述】:

我在这里遇到了一件奇怪的事情:

我在 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 未在挂载中设置

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

【问题讨论】:

  • 你用this.currentLat = position.coords.latitude;改变了它的值
  • 是的,但是当我控制台记录它的值时,它给了我初始值而不是位置纬度
  • 因为它是异步的,所以你应该在回调中使用它,或者将它转换为promise并使用async/await
  • 假设用户屏蔽了他们的地理位置,浏览器会弹出询问权限,回调只有在用户允许他们的地理位置后才会运行

标签: vue.js vuejs2


【解决方案1】:

这是一个转换为 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
},

【讨论】:

    【解决方案2】:

    您的代码是有效的,回调箭头函数是异步的(它不会立即执行)并且console.log(this.currentLat); 的调用是同步的,这使得它在回调上下文之前执行,如果您在内部使用它,该属性是正确的模板可以正常工作

    【讨论】:

    • 那么我需要做什么来解决这个问题?
    • 没有什么可修复的,你的数据遵循正确的模式,如果你想在回调函数内更新后打印你的数据,你可以使用观察者属性
    • 不用担心数据的更新,你的属性在箭头函数中发生变化时是反应性的,变化会反映在 UI 中
    【解决方案3】:

    如下设置回调中的值:

    <template>
      <div id="app">{{ currentLat }} - {{ currentLong }}</div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          currentLat: "intial Lat",
          currentLong: "intial Long",
        };
      },
      mounted() {
        this.getCurrentLocation();
      },
      methods: {
        getCurrentLocation() {
          navigator.geolocation.getCurrentPosition(this.setCoordinates);
        },
        setCoordinates(position) {
          this.currentLat = position.coords.latitude;
          this.currentLong = position.coords.longitude;
        },
      },
    };
    </script>
    

    【讨论】:

    • 理智的事情,回电没有解决它
    • 是的,确实如此,您到底得到了什么?我用一个要测试的版本编辑了答案。
    猜你喜欢
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 2019-05-23
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多