istrib / vuex-typescript

A simple way to make Vuex type-safe with intuitive intellisense
237 stars 18 forks source link

Using strongly typed vuex in other modules #2

Closed mmajcenic closed 7 years ago

mmajcenic commented 7 years ago

Is there any way I can use this vuex-typescript in modules like vue-router, where I do not have access to this.$store? My use case is such that I am checking if user is authenticated by using getter from vuex in beforeEach hook in vue-router

EliaECoyote commented 7 years ago

I personally keep an instance of the vuex store like this

export interface RootState {
  application: ApplicationState;
  session: SessionState;
}

export class StoreManager {

  store: Vuex.Store<any>;

  static instance: StoreManager;

  constructor() {
    this.store = new Vuex.Store<RootState>({
      modules: {
        session: sessionModule,
        application: applicationModule
      },
      strict: true
    });
  }

}

So i can access to the store istance outside Vue instances by using StoreManager.instance

I guess its better to create a Vue plugin to do this though, and then access it with Vue.pluginName

istrib commented 7 years ago

@asulta 's suggestion or a similar one is the way to go. Although there is only one store in Vuex, the library does not explicitly implement it as a generally accessible singleton. vuex-typescript follows Vuex style. For that reason all accessor functions require store instance as an explicit argument.

ghost commented 6 years ago

@asulta Hey i know this has been closed but when i follow your way, i get store is undefined if i call store.instance and nothing works. I really need access to my store in vue-router and I cant. Router is in history mode and it doesnt work what i first load into a route from outside the website. If you could help that would be amazing

EliaECoyote commented 6 years ago

@VikingTrex you should provide a snippet of code so I can better understand the issue.. Also a thing that I didn't mention is that accessing to vuex store directly is not really recommended.

new Vuex.Store returns a vuex store instance, that you can export and import in other files.

// store.js
export const store = new Vuex.Store<RootState>(...)

// anotherFile.js
import { store } from './store.js';
// profit!