Skip to content
Advertisement

How to make Nuxt global object?

I want to create custom object that could be available globally in every place (plugins, middleware, component’s created/computed/mounted methods)

I could access global object with context property (custom plugin, custom router middleware … ),

but how to access it in component’s created() ?

Advertisement

Answer

You can use the store to for global variables:

📄 https://nuxtjs.org/guide/vuex-store


1/ Create store:

JavaScript

2/ Read data store

Then you can get or set var1 & var2, from any <page>.vueor <layout>.vue or <plugin>.vue or <middleware>.vue.

From <template> with $store:

JavaScript

or from <script>with injection on asyncData:

JavaScript

3/ Update data store

JavaScript

4/ Component & Store

From <component>.vue you have not to directly fetch the Store.

So you have to pass data from nuxt file to component file with a custom attribute:

JavaScript

then

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement