在挂载的vuejs之后在数据对象中设置地理位置

Kau*_*win 5 javascript geolocation vue.js

我对VueJS场景比较陌生.最近我正在尝试处理我的方面项目,该项目需要在主要组件安装后立即获取用户的地理位置数据.

我的代码在这里,

var app = new Vue({
  el: '#app', 
  data: {
    position: null
  },
  mounted: function() {
    if(navigator.geolocation){
       navigator.geolocation.getCurrentPosition(function(position){
        this.position = position.coords;
      })
    }

  }
});
Run Code Online (Sandbox Code Playgroud)

我希望position在安装后将数据对象设置为当前的地理位置,但不幸的是它无法正常工作.有什么我想念的吗?

Bel*_*dak 7

这是上下文问题,这个内部导航器被限制在错误的上下文中,所以当你编写时this.position,this不会设置为Vue对象.

为了防止你可以使用箭头功能:

  mounted: function() {
    if(navigator.geolocation){
       navigator.geolocation.getCurrentPosition(position => {
        this.position = position.coords;
      })
    }
  }
Run Code Online (Sandbox Code Playgroud)

或者在保存正确上下文的导航器对象之前对变量进行declate

  mounted: function() {
    if(navigator.geolocation) {
       var self = this;
       navigator.geolocation.getCurrentPosition(function(position){
        self.position = position.coords;
      })
    }
  }
Run Code Online (Sandbox Code Playgroud)

BTW只是让你知道-在position.coords将返回保存如Properties对象latitude,longitude等等,所以如果你想他们中的一个,你需要点:

self.position = position.coords.latitude;
Run Code Online (Sandbox Code Playgroud)