Ahmad Mobaraki
Ahmad Mobaraki

Reputation: 8160

How to create a helper function in NuxtJs to use inside vuex and components?

I want to create a plugin for Nuxtjs to log everything I want only in client mode, something like this :

// ~/plugins/client-log.js
export default ({ app }, inject) => {
    app.clog = string => console.log(string)
}

This plugin is working in components where I have access to context for example:

export default {

  fetch({app}){
       app.clog("some string")
  }
};

But I want to be able to use it inside vuex (actions, mutations...). How can I do that?

Thanks in advance.

Upvotes: 3

Views: 5083

Answers (1)

HMilbradt
HMilbradt

Reputation: 4639

You're so close, you just need to change one thing:

// ~/plugins/client-log.js
export default ({ app }, inject) => {
    inject('clog', string => console.log(string))
}

Then you're able to call it like:

export default {

  fetch({app}){
       // Note: inject will automatically prefix with a "$"
       app.$clog("some string")
  },

  mounted() {
    // this.$clog can also be accessed within vuex
    this.$clog("I'm in a component")
  }
};

Upvotes: 5

Related Questions