const pointTooltip = new mapboxgl.Popup({ className: 'pointTooltip', closeButton: false, closeOnClick: false, anchor: 'left', offset: [15, -5] }) const pointPopup = new mapboxgl.Popup({ className: 'common-popup', anchor: 'bottom', maxWidth: 'none', offset: [0, -40] }) const name = 'point0' this.map.on('mouseenter', name, e => { const features = this.map.queryRenderedFeatures(e.point) this.map.getCanvas().style.cursor = 'pointer' const properties = features[0].properties const position = features[0].geometry.coordinates pointTooltip.setLngLat(position) .setHTML(`<div class = 'tooltip'> <span> ${properties.qlmc}</span> <span>${formatStake(properties.qlzxzh)}</span> </div>`) .addTo(this.map) }).on('mouseleave', name, e => { const remove = () => { this.map.getCanvas().style.cursor = 'grab' pointTooltip.remove() } remove() }) this.map.on('click', name, e => { const features = this.map.queryRenderedFeatures(e.point) const properties = features[0].properties pointPopup.setLngLat(features[0].geometry.coordinates).setDOMContent(setVueComponent(Test, { dataInfo: properties })).addTo(this.map) })优化这段代码
时间: 2024-02-14 10:25:54 浏览: 543
优化这段代码可以考虑以下几点:
1. 将匿名函数改为命名函数,提高代码的可读性和可维护性。
2. 将事件处理函数单独提取出来,以便复用。
3. 使用解构赋值简化代码。
4. 使用箭头函数简化代码。
5. 将重复的代码提取出来,减少重复编写。
下面是优化后的代码:
```javascript
// 定义事件处理函数
const handleMouseEnter = (e) => {
const { point } = e;
const features = this.map.queryRenderedFeatures(point);
this.map.getCanvas().style.cursor = 'pointer';
const { properties, geometry } = features[0];
const { coordinates } = geometry;
pointTooltip.setLngLat(coordinates)
.setHTML(`<div class='tooltip'>
<span>${properties.qlmc}</span>
<span>${formatStake(properties.qlzxzh)}</span>
</div>`)
.addTo(this.map);
};
const handleMouseLeave = () => {
this.map.getCanvas().style.cursor = 'grab';
pointTooltip.remove();
};
const handleClick = (e) => {
const features = this.map.queryRenderedFeatures(e.point);
const { properties, geometry } = features[0];
pointPopup.setLngLat(geometry.coordinates)
.setDOMContent(setVueComponent(Test, { dataInfo: properties }))
.addTo(this.map);
};
// 添加事件监听
this.map.on('mouseenter', name, handleMouseEnter)
.on('mouseleave', name, handleMouseLeave)
.on('click', name, handleClick);
```
通过以上优化,代码更加清晰易读,也方便了后续的维护和修改。同时,通过提取重复的代码,减少了重复编写,提高了代码的可维护性。
阅读全文