Piotr Żak
Piotr Żak

Reputation: 2403

Vuex access this.$store from getters

I'm trying to access this.$store.commit from getters section and I see error property '$store' of undefined, I was able to access this.$store from mutations so why not from getters?

my store.js file

import Vue from 'vue';
import Vuex from 'vuex';
import order from './modules/order/order'
import dialogList from './modules/dialog/dialogList'

Vue.use(Vuex);

export const store = new Vuex.Store({
    state: { },
    getters: {

    },
    modules: {
        order,
        dialogList
    }
});

my order.js file calling mutation from dialogList

const state = {
    order: {
       ...
    }
}

const getters = {
    showInfoDialogWithCalculatedData(state) {
    //... some actions

    //here this.$store is undefined
    this.$store.commit('showInfoDialog', { message: 'test', type: 'error'});
    
    return someData;
    }
}

const mutations = {
    showInfoDialogWithCalculatedData(state) {
    //... some actions

    //here this.$store is defined
    this.$store.commit('showInfoDialog', { message: 'test', type: 'error'});
   
    }
}

export default {
    state,
    getters,
}

Why this.$store is undefined in getters?

Upvotes: 0

Views: 751

Answers (1)

mathieu janio
mathieu janio

Reputation: 36

Because getters should not commit mutation maybe you can setup a watcher so when the getters call an update you can commit or if you REALY want to do it you can import the store and call the commit from the store imported.

import store from "../index";

const getters = {
  showInfoDialogWithCalculatedData(state) {
  //... some actions

  //Store imported
  store .commit('showInfoDialog', { message: 'test', type: 'error'});

  return someData;
}

Upvotes: 2

Related Questions