【问题标题】:Vue.js set component dataVue.js 设置组件数据
【发布时间】:2018-06-29 12:46:22
【问题描述】:

我有一个 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:{}
    }
  },

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

【问题讨论】:

  • 请定义你所说的外部是什么意思?
  • 当我在 updateCurentPosition() 中打印 this.$data.currentLocation 时,该对象有一个 Lat 和 Lng。但是当我设置它后在另一个函数(外部)中打印它时,打印显示一个空白对象。
  • 引用时不要使用$data。只是this.currentLocation
  • 我还是有问题,this.currentLocation 在 updateCurentPosition() 中有正确的 lat & lng,但是当我在另一个函数中打印时它仍然是空白的。
  • 另一个函数在哪里,它使用什么句柄代替this 来获取相同的组件实例?有什么办法可以将其提炼成mcve

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


【解决方案1】:

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

你被 data () { return { currentLocation: null } } 对象弄糊涂了,它告诉 vuejs 在他的反应系统中添加 currentLocation

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

【讨论】:

    猜你喜欢
    • 2016-09-21
    • 2018-09-12
    • 2018-05-24
    • 2017-05-19
    • 1970-01-01
    • 2016-02-12
    • 2016-05-11
    • 2017-06-28
    • 1970-01-01
    相关资源
    最近更新 更多