Nuxt Inject Global Helper Functions or Variables

February 20, 2020

Combined Inject

https://nuxtjs.org/guide/plugins/#combined-inject

Edit nuxt.config.js.

export default {
  plugins: ['~/plugins/inject.js']
}

Edit ~/plugins/inject.js

You can create an object to hold functions or variables.

const test = {
  name: 'Test'
  ping() {
      console.log('Ping')
  }
}

export default ({ app }, inject) => {
  inject('test', test)
}

Access object in components

export default {
  mounted () {
    this.$test.ping()
  },
  /*
  // context - https://nuxtjs.org/api/context/
  asyncData (context) {
    console.log(context.app.$test.name)
  }
   */
  // access context via destructuring assignment
  asyncData ({ app }) {
    console.log(app.$test.name)
  },
}

Access object in plugins

export default ({ app }) => {
  app.$test.ping()
  console.log(app.$test.name)
}

Access object in store.

export const state = () => ({
  testName: null
})

export const mutations = {
  updateTestName(state, value) {
    state.testName = `${this.$test.name}: ${value}`
  },
}

export const actions = {
  testPing({ commit }) {
    this.$test.ping()
    commit('updateTestName', 'ping')
  },
}

Vue.prototype

You can use Vue.prototype if you need the object accessiable via components but not nuxt context.

Edit ~/plugins/inject.js

const test = {
  name: 'Test'
  ping() {
      console.log('Ping')
  }
}

Vue.prototype.$test = test

Vue mixins

https://vuejs.org/v2/guide/mixins.html

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.