首页 > 解决方案 > vuex状态改变时如何重新渲染vue组件?

问题描述

我想创建一个像控制层这样的组件来更改传单的底图。但我不想使用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改变,它只是改变了baseMap非传单组件的值。

这是我的 Map 组件,我用来在更改时computed访问baseMapstate

<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>

我尝试在标签baseMap内调用 value ,当状态改变时,它会改变。<div>但是传单基础层没有改变

<div id="map">{{ baseMap }}</div>

我一直在寻找解决方案,但我仍然感到困惑。我不知道还能做什么。

标签: javascriptvue.jsleafletvue-componentvuex

解决方案


你应该

 watch: {
        baseMap () {
            this.setupLeafletMap()
        }
    },

推荐阅读