【发布时间】:2021-10-28 23:48:12
【问题描述】:
我想创建一个像控制层这样的组件来更改传单的底图。但我不想使用L.control.layers。因此,我制作了一个侧边栏组件,其中包含更改底图的选项。
我使用 vuejs 并使用 vuex 来组织数据。 这是我的代码
store.js
import Vue from 'vue'
import Vuex from 'vuex'
import "leaflet/dist/leaflet.css";
Vue.use(Vuex)
export default new Vuex.Store({
state: {
satellite: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
dark: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png',
osm: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
topography: 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png',
baseMap: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'
},
getters: {
baseMap: state => state.baseMap
},
actions: {
changeBaseMap({ commit }, base) {
commit("CHANGE_BASE_MAP", base);
}
},
mutations: {
CHANGE_BASE_MAP(state, base) {
state.baseMap = base
}
},
})
用于更改baseMap 值的侧边栏组件已工作。但是,当baseMap 状态改变时,leaflet 组件不会改变,它只是改变了baseMap 的值,而不是leaflet 组件。
这是我的地图组件,当state 发生变化时,我使用computed 来访问baseMap 值
<template>
<div id="container" >
<div id="map"></div>
</div>
</template>
<script>
import "leaflet/dist/leaflet.css";
import L from "leaflet";
export default {
name: "Map",
data() {
return {
center: [-0.789275,113.921327],
zoom: 5,
map: null
};
},
computed: {
baseMap: function () {
return this.$store.getters.baseMap
}
},
methods: {
setupLeafletMap () {
this.map = L.map("map").setView(this.center, this.zoom);
var tilelayer = L.tileLayer(this.baseMap)
tilelayer.addTo(this.map)
}
},
mounted() {
this.setupLeafletMap();
}
};
</script>
我尝试在<div> 标签内调用baseMap 值,当状态改变时,它会改变。但是传单基础层没有改变
<div id="map">{{ baseMap }}</div>
我一直在寻找解决方案,但我仍然感到困惑。我不知道还能做什么。
【问题讨论】:
-
据我所知,这是因为
baseMap是反应式的,但这不会影响您的“setupLeafletMap”功能。实际上,您可能需要在每次状态更改时调用该函数。
标签: javascript vue.js leaflet vue-component vuex