Valentin
Valentin

Reputation: 53

Accessing Nuxt plugin function in vuex getter

I am getting started with nuxtjs and vuex. I just encountered an issue accessing a combined injected plugin function from a getter. E.g.:

nuxt.config.js

...
plugins: [
  '~/plugins/myplugin.js'  
  ],
...

~/plugins/myplugin.js

function doSomething(string) {
        console.log("done something: " + string)
    }

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

~/store/index.js

export const actions = {
    someAction({commit}) {
        this.$doSomething("Called from Action") // works
    }
}

export const getters = {
    someGetter: state => {
        this.$doSomething("Called from Getter") // throws error
    }
}

The code works for the action someAction but the call in getter someGetter will result in a error suggesting this is undefined.

The nuxt documentation only shows examples for accessing injected plugin functions from mutations and actions but does not explicitly mention that getters can not access plugin functions. Is this even possible in nuxt or is there a good reason not to call a plugin method in a getter? Any help appreciated.

Upvotes: 4

Views: 4143

Answers (2)

Ronald
Ronald

Reputation: 1039

You shouldn't try to do_something in a getter. Getters are for deriving state from your store's state only. The point being that you don't have to separately store and keep up-to-date the derived state. For example you have a list of tasks and you have a getter for completed tasks instead of a separate list of done tasks: completedTasks: state => state.tasks.filter(task => task.completed).

Mutations should only be used for mutating your store's state.

Finally, in actions you can interact with whatever you need, like a webserver API somewhere or this.$do_something and then fire off mutations to update the state based on the results.

So I'd say it makes sense what Nuxt is doing here, to inject in the actions but not to the getters.

Upvotes: 3

strapro
strapro

Reputation: 163

I faced the same issue and I was able to get around it by doing

export const getters = {
  someGetter: state => {
    $nuxt.$doSomething("Called from Getter") // Grab $nuxt from the global scope
  }
}

Not sure if this works in SSR mode however

Upvotes: 2

Related Questions