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
在安装后将数据对象设置为当前的地理位置,但不幸的是它无法正常工作.有什么我想念的吗?
这是上下文问题,这个内部导航器被限制在错误的上下文中,所以当你编写时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)
归档时间: |
|
查看次数: |
4749 次 |
最近记录: |