Nuxt: Can't access vuex store from js file

Viewed 1635

I'm creating an app with Vuex state management in Nuxt. The problem is I want to create js file with functions, which I will import into my Vue files. I need to access my store in that file.

In functions.js I want to import store using import store from "@/store", but store gives me empty object. When I do import store from "@/store/dice.js", which is store I want to access It return undefined and in a console I got information: "export 'default' (imported as '$store') was not found in '~/store/dice'

@/store/index.js is empty.

@/store/dice.js got structure like in Nuxt tutorial:

export const state = () => ({
list: []
})

export const mutations = {
add(state, text) {
state.list.push({
text,
done: false
})
},
remove(state, { todo }) {
state.list.splice(state.list.indexOf(todo), 1)
},
toggle(state, todo) {
todo.done = !todo.done
}
}

Can anyone help?

1 Answers

Vuex Store files located in store directory will be transformed by Nuxt to become a store instance when build time.

So you can't import any files from them into other js files outside the store.

You have to solutions:

  1. Which is recommended: Add your function.js folder into your store and use your functions there (call them inside mutations, actions, etc...)
  2. Which is NOT recommended: When calling your functions in function.js pass your store instance as a parameter, then you can use it.
Related