【问题标题】:GeoJSON - Method within onEachFeatureGeoJSON - onEachFeature 中的方法
【发布时间】:2018-07-25 17:11:14
【问题描述】:

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"
        });
    });
}

【问题讨论】:

    标签: vuejs2 leaflet


    【解决方案1】:

    你可以 bind 你的 onEachFeature 函数到你的 Vue 对象:

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

    this in onEachFeature 然后将引用您的 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/

    【讨论】:

    • tnx,但似乎该方法仅在初始化期间运行
    • 在我的例子中,是的,因为 onEachFeature 是在初始化而不是鼠标事件时调用的。我已经修改了这个例子来展示如何在鼠标悬停时引用 Vue 对象。
    • 已经帮了我很多忙了!现在我只需要动态改变对象的样式(my current Fiddle
    猜你喜欢
    • 2018-07-28
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多