I have a Map.vue component, and I would like to change its data. However I don't know how to do this in Vue.js :
<template>
<div>
<div class="google-map" :id="mapName">
</div>
</div>
</template>
<script>
export default {
name: 'google-map',
props: ['name'],
methods:{
updateCurrentPosition(){
navigator.geolocation.getCurrentPosition((position) => {
this.$data.currentLocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
console.log("After setting, This.currentLocation = ");
console.log(this.$data.currentLocation);
this.map.panTo(new google.maps.LatLng(this.$data.currentLocation.lat, this.$data.currentLocation.lng));
this.map.setZoom(18);
});
},
initializeMap(){
this.updateCurrentPosition();
console.log("Before Marker, This.currentLocation = ");
console.log(this.$data.currentLocation);
this.addMarker(this.$data.currentLocation);
},
addMarker(LatLngObj){
console.log("In addMarker This.currentLocation = ");
console.log(this.$data.currentLocation);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(LatLngObj.lat, LatLngObj.lng),
map:this.map,
icon:'http://www.magic-emoji.com/emoji/images/619_emoji_iphone_ok_hand_sign.png'
});
}
},
data: function () {
return {
mapName: this.name + "-map",
markerCoordinates: [{
latitude: 51.501527,
longitude: -0.1921837
}, {
latitude: 51.505874,
longitude: -0.1838486
}, {
latitude: 51.4998973,
longitude: -0.202432
}],
map: null,
bounds: null,
markers: [],
currentLocation:{}
}
},
this.$data.currentLocation has a correct value in updateCurentPosition(), but once outside this function, it is just a blank object. How can I set its value so it accessible from other functions ?
Use this.currentLocation
instead of this.$data.currentLocation
.
You've been confused by data () { return { currentLocation: null } }
object which tell vuejs to add currentLocation
in his reactivity system.
But all properties defined in this data object are accessible directly by this
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.