首页 > 解决方案 > GeoJSON - onEachFeature 中的方法

问题描述

Vue2Leaflet是一个在 Vue2 框架中实现 Leaflet 的库;能够在地图上显示 GeoJSON 对象。

对于多个 GeoJSON 行,我想要一个影响其他行样式的鼠标单击事件(例如,它切换一个selectedLineId变量)。我设法在鼠标悬停时改变了 geojson 线条的样式;看到这个JSFiddle

核心是onEachFeature将鼠标悬停事件添加到每个功能。但我不知道如何从这里运行 Vue 方法;

function onEachFeature (feature, layer) {
    layer.on('mouseover', function (e) {
        e.target.setStyle({
            color: "#FF0000"
        });
    });
    layer.on('mouseout', function (e) {
        e.target.setStyle({
            color: "#000000"
        });
    });
}

标签: vuejs2leaflet

解决方案


你可以将你的函数绑定onEachFeature到你的 Vue 对象:

data() {
    return {
        // ...
        lines: {
            geojson: geojsondata,
            options: {
                onEachFeature: onEachFeature.bind(this),
                style: {
                    color: "#000000"
                }
            }
        }
    }
}

this然后inonEachFeature将引用您的 Vue 对象:

function onEachFeature (feature, layer) {
    var v = this;

    layer.on('mouseover', function (e) {
        // assuming you have a getColor method defined
        e.target.setStyle({
            color: v.getColor()
        });
    });
    layer.on('mouseout', function (e) {
        e.target.setStyle({
            color: "#000000"
        });
    });
}

这是一个更新的小提琴:https ://jsfiddle.net/qywaz1h8/96/


推荐阅读