Access Nuxt `$config` within Vuex State
Asked Answered
V

1

10

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?

Velours answered 5/4, 2021 at 23:20 Comment(0)
B
11

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)
  }
}

Becerra answered 6/4, 2021 at 2:5 Comment(3)
How would one handle typing errors associated with accessing instance properties in this case? Eg Property '$config' does not exist on type 'Vue'. Thanks.Wheelsman
$config is a property of context, which is defined in @nuxt/types.Context. So when you pass in the context as an argument, import {Context} from "@nuxt/types" and use Context as the argument type.Becerra
Yup, augmented Vue class with extra $config field and using that as a type definition for context, works as expected. Thank you.Wheelsman

© 2022 - 2024 — McMap. All rights reserved.