Vue.use() is throwing "Cannot read property 'use' of undefined"

16.9k Views Asked by At

Attempt 1

main.js

import { createApp } from 'vue'
import { store } from './store/store'
import App from './App.vue'

Vue.config.productionTip = false

const app = createApp(App)

app.use(store)

app.mount('#app')

store.js

import Vuex from 'vuex'
import Vue from 'vue'

Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {
    patients: []
  }
});

Attempt 1 Error

Uncaught TypeError: Cannot read property 'use' of undefined
    at eval (store.js?07a4:4)
    at Module../src/store/store.js (app.js:1342)

Attempt 2

main.js

import { createApp } from 'vue'
import { store } from './store/store'
import App from './App.vue'

Vue.config.productionTip = false

const app = createApp(App)

app.use(store)

app.mount('#app')

store.js

import Vuex from 'vuex'
import Vue from 'vue'

export const store = new Vuex.Store({
  state: {
    patients: []
  }
});

Attempt 2 Error

vuex.esm.js?94ea:135 Uncaught Error: [vuex] must call Vue.use(Vuex) before creating a store instance.
    at assert (vuex.esm.js?94ea:135)
    at new Store (vuex.esm.js?94ea:380)
    at eval (store.js?07a4:6)

I created a Vue application using Vue CLI. I am trying to implement Vuex. I have followed numerous tutorials (usually set up 2 different ways). When using a debugger, I was able to stop before it read "Vue.use(Vuex)". Logging Vue at this point returns undefined. I believe my imports are correct but do not know if I am missing something crucial. Any help is much appreciated.

EDIT: The only difference between Attempt 1 and 2 is I removed "Vue.use(Vuex)" on Attempt 2.

2

There are 2 best solutions below

1
On

I was able to get this working by uninstalling my VueX (3.6)

npm uninstall vuex

and installing the VueX (4.0 alpha)

npm i [email protected]

The reason for this error was because I was using 2 different syntax methods from different versions.

Thanks for everyone's help!

main.js

import { createApp } from 'vue'
import { store } from './store/store'
import App from './App.vue'

const app = createApp(App)

app.use(store)

app.mount('#app')

store.js

import { createStore } from 'vuex'

// Create a new store instance.
const store = createStore({
  state () {
    return {
      patients: []
    }
  }
})

export default store;
4
On

You're using vuex 3 syntax with Vue 3 which is compatible with vuex 4 that has the following syntax :

store.js


import { createStore } from 'vuex'

// Create a new store instance.
const store = createStore({
  state: {
    patients: []
  }
})
export default store;

then use the exported store in the main.js :

import { createApp } from 'vue'
import store from './store/store'
import App from './App.vue'

Vue.config.productionTip = false

const app = createApp(App)

app.use(store)

app.mount('#app')

Vuex 4 docs

Vue.js 3 docs