【问题标题】:Uncaught TypeError: Cannot read property 'removeLayer' of undefined Vue and Leaflet未捕获的类型错误:无法读取未定义的 Vue 和 Leaflet 的属性“removeLayer”
【发布时间】:2018-07-30 00:38:33
【问题描述】:

我正在制作一个 vue 项目,我想在我的组件中使用传单。我得到了显示的地图,我可以添加标记,但是当我尝试添加调用函数以删除标记时遇到错误。我明白了

未捕获的类型错误:无法读取未定义的属性“removeLayer” 在 HTMLInputElement.eval (VM43035 App.vue:118) 在 HTMLInputElement.dispatch (jquery.js:3058) 在 HTMLInputElement.eventHandle (jquery.js:2676)

<template>
 <div id="app" class="container-fluid">
 <div class="row">
  <div class="col-md-9">
    <div id="map" class="map" style="height: 781px;"></div>
  </div>
  <div class="col-md-3">

  </div>
</div>

<router-view/>
</div>
</template>

<script>
export default {
name: "App",
data() {
return {
  map: null,
  marker: null,
  mapSW: [0, 4096],
  mapNE: [4096, 0]
 },
mounted() {
 this.initMap();
 this.initLayers();
 this.onClick();
 this.onPopupOpen();
},
computed: {
  popupContent: function() {
    return "<input type='button' value='Delete' class='marker-delete-button' /> <br> <input type='button' value='Add Event' class='marker-delete-button'/>";
}
 },
 methods: {
  initMap() {
  this.map = L.map("map").setView([0, 0], 1);
  this.tileLayer = L.tileLayer("/static/map/{z}/{x}/{y}.png", {
    maxZoom: 4,
    minZoom: 3,
    continuousWorld: false,
    noWrap: true,
    crs: L.CRS.Simple
  });
  this.tileLayer.addTo(this.map);
  this.map.on("click", this.onClick, this);


  this.map.setMaxBounds(
    L.LatLngBounds(L.latLng(this.mapSW), L.latLng(this.mapNW))
  );
},
initLayers() {},
onClick(e) {
  this.marker = L.marker(e.latlng, {
    draggable: true
  })
    .addTo(this.map)
    .bindPopup(this.popupContent);
  this.marker.on("click", this.onPopupOpen, this);
},
onPopupOpen() {
  $(".marker-delete-button:visible").click(function() {
    this.map.removeLayer(this.marker);
  });
  }
}
};

</script>

【问题讨论】:

  • 在这种情况下,this 指向 DOM 元素,而不是组件。
  • 我建议在某个时候通读重复的帖子,但在您的情况下,快速解决方法是在 onPopupOpen 方法中的 click 回调中使用箭头函数:@987654326 @。箭头函数中对 this 的引用与父范围(在您的情况下是 Vue 实例)相同。

标签: javascript vue.js leaflet


【解决方案1】:

正如 Itamajas 指出的,这绑定到 DOM 元素,而不是你的 vue 实例。

我建议:

onPopupOpen() {
  const map = this.map
  const marker = this.marker
  $(".marker-delete-button:visible").click(function() {
    map.removeLayer(marker);
  });
}

【讨论】:

  • 这有点用,但它会删除我放置的最后一个标记。我怎样才能让它删除任何标记?
猜你喜欢
  • 2018-07-29
  • 1970-01-01
  • 2018-07-31
  • 2020-09-18
  • 2021-05-03
  • 2021-04-03
  • 1970-01-01
  • 2021-12-22
  • 2015-01-06
相关资源
最近更新 更多