championswimmer / vuex-module-decorators

TypeScript/ES7 Decorators to create Vuex modules declaratively
https://championswimmer.in/vuex-module-decorators/
MIT License
1.8k stars 170 forks source link

Unable to use Vuex Store in layouts #331

Open munjalpatel opened 3 years ago

munjalpatel commented 3 years ago

I am trying to use Vuex Store in my layout but can't figure out how to make it work. Here is what I am doing:

store/sources.ts

import { VuexModule, Module, Mutation, Action } from 'vuex-module-decorators'
import { store } from '@/store'
import axios from 'axios'

const { sourcesEndpoint } = process.env

interface Source {
  id: String
}

@Module({
  name: 'sources',
  namespaced: true,
  stateFactory: true,
  dynamic: true,
  store,
})
export default class Sources extends VuexModule {
  private _sources: Source[] = []

  get sources(): Source[] {
    return this._sources
  }

  @Mutation
  updateSources(sources: Source[]) {
    this._sources = sources
  }

  @Action({ commit: 'updateSources' })
  async fetchSources() {
    // eslint-disable-next-line no-console
    console.log(`!!! ${sourcesEndpoint} !!!`)
    return sourcesEndpoint ? await axios.get(sourcesEndpoint) : []
  }
}

store/index.ts

import { Store } from 'vuex'

export const store = new Store({})

layouts/default.vue

<script>
import { getModule } from 'vuex-module-decorators'
import Sources from '@/store/sources'

export default {
  fetch() {
    const sourcesModule = getModule(Sources, this.$store)
    sourcesModule.fetchSources()
  },

  fetchOnServer: false,
}
</script>

And the error I get:

[vuex] must call Vue.use(Vuex) before creating a store instance.
hrebet commented 3 years ago

@munjalpatel, Hello!

Tell me please, is there any progress with this? This is a big problem for me now.

hrebet commented 3 years ago

I found a temporary solution.

"Lazy" loading of components that use Store.

layouts/default.vue

<template>
  <Component :is="componentWithStore" />
</template>

<script lang="ts">
import { Component, Vue } from 'nuxt-property-decorator'

@Component()
export default class extends Vue {
  get componentWithStore (): () => Promise<any> {
    return () => import('./ComponentWithStore.vue')
  }
}
</script>

Your suggestions?

riaanduplessis commented 3 years ago

Are you actually calling Vue.use(Vuex) somewhere before the store is instantiated as the error message suggested?

[vuex] must call Vue.use(Vuex) before creating a store instance.