Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Nuxt `$config` within Vuex State

Tags:

nuxt.js

vuex

According to the Nuxt docs, I should be able to access $config from within my vuex store:

"Using your config values: You can then access these values anywhere by using the context in your pages, store, components and plugins by using this.$config or context.$config." (emphasis added, from https://nuxtjs.org/docs/2.x/directory-structure/nuxt-config#runtimeconfig)

When I try to access $config in my store like this:

export const state = () => (
    {
        // App vital details
        app: {
            name: 'MyApp',
            appVersion: this.$config.appVersion,
            copyright: helpers.getCurrentYear()
        },
    }
)

I get an error message in the console: "Cannot read property '$config' of undefined" If I try with context.$config I get error: "context is not defined"

I know $config is "working" otherwise because I can access it in my templates with $config.appVersion, but how can I properly access it within my store?

like image 755
solidau Avatar asked Mar 01 '23 16:03

solidau


1 Answers

Unfortunately it’s not that simple— you can’t access $config from the store without first passing the context instance in. You can do this easily enough via an action, or nuxtServerInit.

If you’re using SSR:

actions: {
  nuxtServerInit (vuexContext, { $config }) {
    // your code...
  }
}

Otherwise you can pass the context in by dispatching an action called from elsewhere within your app. Eg. from a page with asyncData:

page-example.vue

asyncData(context) {
  context.store.dispatch('loadInActionExample', { data: 'test', context: context })
}
Your store (index.js or action module)

export const actions = {
  loadInActionExample(context, payload) {
    // payload.context.$config is accessible...
 
    // execute your action and set data
    context.commit('setData', payload.data)
  }
}

like image 50
Nick Dawes Avatar answered Mar 18 '23 12:03

Nick Dawes