<map id="map" ref="map" :scale="16" style="width:750rpx;height:100vh;" @markertap="onMarkerTap" :latitude="markers[0].latitude" :longitude="markers[0].longitude" :markers="markers" :center="center"></map>data() {return {markers:[{id: 1,latitude:30.572245,longitude:114.351136,},{id:2,latitude:30.572043,longitude:114.348478,}],}},goToTaskDetail() {if (passType === 9) {var markers = [{ id: 0, latitude: 30.572245, longitude: 114.351136, iconPath: (), width: 32,height: 32, title: '无' },{ id: 3, latitude: 30.572245, longitude: 114.351136, iconPath: (), width: 32,height: 32, title: '3' },{ id: 20, latitude: 30.570861, longitude: 114.350871, iconPath: (), width: 32,height: 32, title: '20' },{ id: 21, latitude: 30.572043, longitude:114.348478, iconPath: (), width: 32,height: 32, title: '21' },,];this.markers = markers},})}onMarkerTap(event) {var markerId = event.markers.id;console.lo("Marker " + markerId + " is tapped.");}, uniapp中,以上代码在点击图标时报错:TypeError: Cannot read property '0' of undefined,请修改到能正常使用
时间: 2023-12-06 16:45:16 浏览: 103
微信小程序实际案例详解:页面搭建
根据代码分析,可能是因为在`goToTaskDetail()`函数中重新定义了`markers`数组,但是在`data()`函数中定义的`markers`数组并没有被更新,导致`onMarkerTap()`函数中调用`markers[0]`时出现了报错。为解决此问题,需要将`markers`数组的定义放到公共的地方,比如在`data()`函数中定义为`this.markers`,并在`goToTaskDetail()`函数中更新`this.markers`的值,以确保`onMarkerTap()`函数中能够正常调用`markers`数组。修改后的代码如下:
```
<map id="map" ref="map" :scale="16" style="width:750rpx;height:100vh;" @markertap="onMarkerTap" :latitude="markers[0].latitude" :longitude="markers[0].longitude" :markers="markers" :center="center"></map>
data() {
return {
markers:[
{id: 1,latitude:30.572245,longitude:114.351136,},
{id:2,latitude:30.572043,longitude:114.348478,}
]
}
},
goToTaskDetail() {
if (passType === 9) {
var markers = [
{
id: 0,
latitude: 30.572245,
longitude: 114.351136,
iconPath: (),
width: 32,
height: 32,
title: '无'
},
{
id: 3,
latitude: 30.572245,
longitude: 114.351136,
iconPath: (),
width: 32,
height: 32,
title: '3'
},
{
id: 20,
latitude: 30.570861,
longitude: 114.350871,
iconPath: (),
width: 32,
height: 32,
title: '20'
},
{
id: 21,
latitude: 30.572043,
longitude:114.348478,
iconPath: (),
width: 32,
height: 32,
title: '21'
}
];
this.markers = markers;
}
}
onMarkerTap(event) {
var markerId = event.markerId;
console.log("Marker " + markerId + " is tapped.");
}
```
在修改后的代码中,`goToTaskDetail()`函数中更新了`this.markers`的值,`onMarkerTap()`函数中获取`markerId`的方式也做了相应的修改。同时,需要注意函数中的其他逻辑是否正确,比如`iconPath`等参数是否正确设置。
阅读全文