简体   繁体   English

Vue.js设置组件数据

[英]Vue.js set component data

I have a Map.vue component, and I would like to change its data. 我有一个Map.vue组件,我想更改其数据。 However I don't know how to do this in Vue.js : 但是我不知道如何在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. this。$ data.currentLocation在updateCurentPosition()中具有正确的值,但在此函数之外,它只是一个空白对象。 How can I set its value so it accessible from other functions ? 如何设置其值,以便可以从其他功能访问它?

Use this.currentLocation instead of this.$data.currentLocation . 使用this.currentLocation代替this.$data.currentLocation

You've been confused by data () { return { currentLocation: null } } object which tell vuejs to add currentLocation in his reactivity system. 您对data () { return { currentLocation: null } }对象感到困惑,该对象告诉vuejs在他的反应性系统中添加currentLocation

But all properties defined in this data object are accessible directly by this . 但是,在这个数据对象定义的所有属性是通过直接访问this

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM