Vue.js设置组件数据

时间:2018-01-20 10:59:51

标签: javascript ecmascript-6 vue.js vuejs2 components

我有一个Map.vue组件,我想更改其数据。但是我不知道如何在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:{}
    }
  },

这个。$ data.currentLocation在updateCurentPosition()中有一个正确的值,但是一旦在这个函数之外,它只是一个空白对象。如何设置其值以便从其他函数访问?

1 个答案:

答案 0 :(得分:0)

使用this.currentLocation代替this.$data.currentLocation

您已被data () { return { currentLocation: null } }对象混淆,该对象告诉vuejs在其反应系统中添加currentLocation

但是this可以直接访问此数据对象中定义的所有属性。