Vuex Module Initialization Best Practice
Asked Answered
K

2

7

(updated with additional background)

I have a Vuex store module that needs to load its data at the beginning of time, automatically, so it's available when requested (in this case it's a 'settings' store that loads data from electron-settings at startup, but there are lots of reasons why I might need something like this).

Right now I'm achieving this by setting up a special 'init' action on my store module and dispatching it from my Main.vue component on the 'mounted' lifecycle hook, like this:

mounted() {
    this.$store.dispatch('initSettings');
}

What I was hoping for is a way the module could simply initialize itself. Ideally, something like a lifecycle hook akin to the 'mounted' hook on my component, but triggered within the vuex store module. This way users of my module would not need to know they must call 'init' as well as instantiating it.

I've searched through the docs and haven't come across a solution for this, but in case I'm just searching for the wrong thing, I was hoping someone out there has found an elegant way to do this.

Killiecrankie answered 30/5, 2018 at 19:54 Comment(0)
G
-2

i needed something similar and my solution is to run is when the document is loaded:

var app_store = new Vuex.Store({
  state: state,
  getters: getters,
  mutations: mutations,
  actions: actions,  	
});

$(document).ready(function()
{  
  app_store.dispatch("initSettings",null); 
});
Grume answered 19/6, 2018 at 12:8 Comment(1)
While the question was really "is there a better way", the answer appears to be no, so marking this as the correct answer to be tidy.Killiecrankie
L
-1

If your store is in a separate file store/index.js, you can just import it.

import store from '/store';

store.dispatch("stuff")

This is because ES6 imports are references and bind to the runtime data structure. The following import store from '/store' statements will get the same reference as the first.

require() makes copies. It's a notable difference.

Londalondon answered 26/11, 2019 at 18:12 Comment(0)
G
-2

i needed something similar and my solution is to run is when the document is loaded:

var app_store = new Vuex.Store({
  state: state,
  getters: getters,
  mutations: mutations,
  actions: actions,  	
});

$(document).ready(function()
{  
  app_store.dispatch("initSettings",null); 
});
Grume answered 19/6, 2018 at 12:8 Comment(1)
While the question was really "is there a better way", the answer appears to be no, so marking this as the correct answer to be tidy.Killiecrankie

© 2022 - 2024 — McMap. All rights reserved.