vue.jsvuexvuejs3vue-composition-apivuex4

Vue 3 - How to dispatch to Vuex store in setup


I have a project where I use Vue 3 and Vuex. This is my first time using Vue 3. I can't seem to get how to access Vuex inside the Setup method of a Vue 3 project.

I have a feature object. That is being set by a Childcomponent using the featureSelected method. Firstly in my setup I create a store constant with useStore; from import { useStore } from "vuex";. Then inside the featureSelected function I call the dispatch function on this store object store.dispatch("setPlot", { geometry: newFeature });.

I keep on getting an error telling me that the dispatch function does not exist on the store object: Uncaught TypeError: store.dispatch is not a function.

  setup() {
    const store = useStore;

    const feature = ref();

    const featureSelected = (newFeature) => {
      feature.value = newFeature;
      store.dispatch("setPlot", { geometry: newFeature });
    };

    return { feature, featureSelected };
  },

Solution

  • useStore is a composable function which should be called using () like :

      const store = useStore();