由于地图组件和控制图层的组件不是父子组件,想利用vuex进行相关地图状态控制。但是无法修该地图状态,求大神看一下。
//store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import mapconfig from '@/config/mapconfig.js'
Vue.use(Vuex)
const state = {
baseLayer: mapconfig.streetmap(0)
};
const getters = {//实时监听state值的变化(最新状态)
layers(state) {
return state.baseLayer
}
};
const mutations = {
changeBaseLayer (state,index) {
state.baseLayer = mapconfig.streetmap(index)
}
}
const actions = {
}
const store = new Vuex.Store({
state,
mutations,
actions,
getters
});
export default store
//mapconfig.js
var streetmap = function(maptype) {
var maplayer = null;
var reNumber = /^[0-9]+.?[0-9]*$/; //数字判断
if (reNumber.test(maptype)){
switch (maptype){
case 0:
maplayer = new TileLayer({
source: new OSM()
})
break;
case 1:
maplayer = new TileLayer({
source:new TileArcGISRest({
url:'https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer'
})
})
break;
}
}
return [maplayer];
}
在这个vue组建中点击切换图层的事件,将要切换的底图作为参数传入,在state中进行改变
<script>
import mapConfig from '@/config/mapconfig.js'
import { mapMutations } from 'vuex'
const baseMaps = mapConfig.leftTopBaseLayers
export default {
name: 'leftTop',
data () {
return {
dataTree: mapConfig.vectorLayers, //树结构的数据
dataBaseMapCheckList: baseMaps, //底图数据
checkedBaseMap: baseMaps[0].url,
isHighLight: true,
tabIndex: 0 //切换标签的值,默认为0
}
},
mounted() {
console.log( mapConfig.leftTopBaseLayers)
},
components: {
},
methods: {
...mapMutations([
'changeBaseLayer'
]),
//上部标签发生变化
changeTabIndex(index) {
this.tabIndex = index
},
changeRadio(data) {
console.log(data)
this.$store.commit('changeBaseLayer',data);
}
},
computed: {
}
}
</script>
这里点击后,state发生了改变
但是地图控件中没有变化,不知道是该怎么绑定这个state的值才能变化呀,以下是地图控件
<template>
<div ref="mapCont" id='map'></div>
</template>
<script>
import Vue from 'vue'
import 'ol/ol.css';
import { Map, View } from 'ol';
import OSM from 'ol/source/OSM';
import TileLayer from 'ol/layer/Tile';
import mapconfig from '../../config/mapconfig.js'
import { mapState } from 'vuex'
export default {
name: 'map-component',
data() {
return {
map: null
}
},
//页面渲染完成后
mounted() {
var mapcontainer = this.$refs.mapCont;
this.map = new Map({
target: this.$refs.mapCont,
layers: baseLayer,
view: new View({
projection: "EPSG:4326",
zoom: mapconfig.view.zoom,
center: [mapconfig.view.x, mapconfig.view.y]
})
});
},
computed: {
...mapState({
baseLayer: state => state.baseLayer
})
}
}
</script>
解决了 少了个this 并且openlayers不支持响应式 要手动设置更新地图