How to setup a centralized state for a mapbox map in Vuex?

前端 未结 1 822
借酒劲吻你
借酒劲吻你 2021-01-05 15:30

I just started using vuex with vue. I do (roughly) understand the docs. I have a specific issue for which I am not sure whether I should use vuex and if so how to go about.<

相关标签:
1条回答
  • It seems to me is new mapboxgl.Map() is an asynchronous function and in vuex Actions can contain arbitrary asynchronous operations not mutations not from mutations. mutation handler functions must be synchronous.

    So you should do new mapboxgl.Map() in actions like following:

    import simple from '../../components/simplestyle'
    let mapboxgl = require('mapbox-gl/dist/mapbox-gl.js')
    
    // initial state
    const state = {
      myMap: {},
      mapLoaded: false
    }
    
    const mutations = {
      loadMap (state, myMap) {
        state.myMap = myMap
      }
    }
    
    const actions = {
      loadMap (context) {
        'use strict'
        mapboxgl.accessToken = 'mysecretmapboxkey'
        var myMap = new mapboxgl.Map({
          container: 'map',
          style: simple,
          hash: true,
          center: [-74.0073, 40.7124],
          zoom: 16
        })
        context.commit('loadMap', myMap)
      }
    }
    
    export default {
      state,
      mutations,
      actions
    }
    

    Edit:

    Given your mouse interactions are causing change in the state, you can have a computed property in you vue instance with getter and setter, like following:

    computed: {
      myMapForView: {
        // getter
        get: function () {
          return this.$store.state. myMap
        },
        // setter
        set: function (newMap) {
          this.$store.commit('loadMap', newMap)
        }
      }
    }
    

    Working Fiddle : http://jsfiddle.net/aucqteLn/

    Also check: Vuex store with "strict: true" does not work

    0 讨论(0)
提交回复
热议问题