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:

// your-project/store/index.js

export const state = () => ({
  var1: null,
  var2: null
})

export const mutations = {
  SET_VAR_1 (state, value) {
    console.log('SET_VAR_1', value)
    state.var1 = value
  },
  SET_VAR_2 (state, value) {
    console.log('SET_VAR_2', value)
    state.var2 = value
  }
}

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:

// your-project/pages/index.js

<template>
  <section>
    <h2>From Store</h2>
    <div>var1 = {{ $store.state.var1 }}</div>
    <div>var2 = {{ $store.state.var2 }}</div>
  </section>
</template>

or from <script>with injection on asyncData:

// your-project/pages/index.js

<template>
  <section>
    <h2>From Store</h2>
    <div>var1 = {{ var1 }}</div>
    <div>var2 = {{ var2 }}</div>
  </section>
</template>

<script>
export default {
  async asyncData ({ store }) {
    return {
      var1: store.state.var1,
      var2: store.state.var2
    }
  }
}
</script>

3/ Update data store

<script>
export default {
  async asyncData ({ store }) {

    store.commit('SET_VAR_1', 'foo')
    store.commit('SET_VAR_2', 'bar')
  }
}
</script>

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:

// your-project/pages/example.js

<template>
  <section>
    <my-component :var1="$store.state.var1" :var2="$store.state.var2" />
  </section>
</template>

then

// your-project/components/MyComponent.js
<template>
  <section>
    <h2>From props</h2>
    <div>var1 = {{ var1 }}</div>
    <div>var2 = {{ var2 }}</div>
  </section>
</template>

<script>
  export default {
    props: ['var1', 'var2']
  }
</script>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement