Javascript Vue-无法将HTML地理位置绑定到组件变量
我遇到了一个奇怪的问题,当我得到一个HTML地理位置调用的结果时,我无法将其绑定到Vue数据,但我可以成功地将其console.log Vue方法:Javascript Vue-无法将HTML地理位置绑定到组件变量,javascript,html,vue.js,geolocation,Javascript,Html,Vue.js,Geolocation,我遇到了一个奇怪的问题,当我得到一个HTML地理位置调用的结果时,我无法将其绑定到Vue数据,但我可以成功地将其console.log Vue方法: initGeolocation: function() { if( navigator.geolocation ) { // Call getCurrentPosition with success and failure callbacks
initGeolocation: function() {
if( navigator.geolocation )
{
// Call getCurrentPosition with success and failure callbacks
navigator.geolocation.getCurrentPosition( success, fail );
}
else
{
return;
}
function success(position)
{
console.log(position.coords.latitude); //works
this.lat = position.coords.latitude; //does not work
}
function fail()
{
console.log('fail')
}
},
mounted() {
this.lat = this.initGeolocation(); // does not work
console.log(this.initGeolocation()) // returns undefined
},
数据:
非常感谢您提供的任何帮助。在您的安装中,您将通过返回initGeolocation方法来分配this.lat。但是,如果此方法成功,则不会返回任何数据。相反,您将结果写入this.lat,然后它将被方法的void结果再次覆盖。因此,请确保您的方法initGeolocation返回您的地理位置数据,或者更改装入的方法以调用该方法,而不将返回值分配给this.lat
另外,您似乎刚刚将initGeolocation方法添加到组件中。查看vue组件的methods属性,它将属于这些组件
因此,请尝试以下方法:
mounted() {
this.initGeolocation();
console.log(this.initGeolocation());
},
methods: {
initGeolocation: function() {
if( navigator.geolocation)
{
// Call getCurrentPosition with success and failure callbacks
navigator.geolocation.getCurrentPosition( success, fail );
}
else
{
return;
}
function success(position)
{
this.lat = position.coords.latitude; //does not work
}
function fail()
{
console.log('fail')
}
}
}
这个词指的是功能的范围。当您在其中嵌套另一个函数时,this这个词现在指的是新的/更小的作用域,因此不再定义this.lat。因此,我们在vm中捕获并在函数中使用它
methods: {
initGeolocation: function() {
var vm = this;
if( navigator.geolocation)
{
// Call getCurrentPosition with success and failure callbacks
navigator.geolocation.getCurrentPosition( success, fail );
}
else
{
return;
}
function success(position)
{
vm.lat = position.coords.latitude; //should work now!!
}
function fail()
{
console.log('fail')
}
}
},
mounted() {
this.initGeolocation();
},
您是否尝试过将成功和失败回调直接添加到函数中?可能this关键字不再引用vue实例,因此this.lat没有访问数据变量
methods: {
initGeolocation: function() {
var vm = this;
if( navigator.geolocation)
{
// Call getCurrentPosition with success and failure callbacks
navigator.geolocation.getCurrentPosition( success, fail );
}
else
{
return;
}
function success(position)
{
vm.lat = position.coords.latitude; //should work now!!
}
function fail()
{
console.log('fail')
}
}
},
mounted() {
this.initGeolocation();
},