Nuxt Inject Global Helper Functions or Variables

Feb 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

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.