【发布时间】: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