Search code examples
vue.jsvuexvuejs3

Getting a Uncaught TypeError: Cannot read property 'use' of undefined on Vue.use(Vuex)


In my vue frontend i tried to setup Vuex. On my store page (inside the store dir, file name index.js).Im using Vue 3.0 When i run the code i get the Cannot read property 'use' of undefined on Vue.use(Vuex) line

This is the chunk of the code

import Vue from "vue";
import Vuex from "vuex";
import Api from "../services/api";

Vue.use(Vuex);//here i get the error

export default new Vuex.Store({
  state:{
  articles:[]
  },...

Solution

  • You need to use Vuex 4 to be Vue 3 compatible, and Vuex 4 introduced a few breaking changes, and one of them is how to initialize the store. Basically instead of using new Vuex.Store, you now use createStore to create the store object and no need to use Vue.use(Vuex) anymore in your store.js.

    import { createStore } from 'vuex';
    
    export const store = createStore({
      state: {...}
      // other stuff
    })
    

    And in your main.js file:

    import { createApp } from 'vue';
    import { store } from 'path/to/store.js';
    
    const app = createApp({...})
    app.use(store);
    

    You can also see the full Vuex 4 example on github