Home

Issue: 2807

Does this service belong in a plugin?

[issue link]

I’ve got two relatively simple questions about the function of plugins from someone just starting with Nuxt. I’m trying to create service with a set of methods that can be called in response to user actions in the browser. These methods need to be able to access the store.

Ideally I have a file util.js with the following:

import store from '~store'

module.exports = {
  actionA () {
    store.commit('a')
  },
  actionB () {
    store.commit('b')
  }
}

However, from my understanding the only way to pass the store to a plugin is through using unnamed exports like example below. Also, in this case the code is invoked immediately and doesn’t expose a method with context that I can use later on:

export default ({ store }) => {
    store.commit('a')
}

A) Functionally, should this ‘service’ be a plugin? My understanding is that plugins are intended to be run before the app is instantiated, while I am just looking to expose a set of methods that can be invoked on-demand client-side. If I were to create this in /services/util.js would there be any way to import the global store there?

B) If it does make sense to wrap this service in a plugin, is there anyway to access store in plugin while still using named exports? I’d hope to avoid having to create a separate file for every instance.

This question is available on Nuxt.js community (#c2436)