Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly set up Vuex in a Vuejs application?

I'm creating a Vuejs application and I want to use Vuex.

But I couldn't add the Vuex store.

This is my code:

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

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    userData: "USER!"
  },
  mutations: {

  },
  actions: {

  },
  getters: {

  }
})

export default store

I'm getting an error:

Uncaught SyntaxError: The requested module '/node_modules/.vite/vue.js?v=52de2cee' does not provide an export named 'default'

main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from '@/router'
const app = createApp(App)
import Vuex from 'vuex'
import { store } from '@/store/users'

app.use(router)
app.use(Vuex)

app.mount('#app')

What I'm doing wrong? Thanks a lot.

like image 889
user467566 Avatar asked Dec 09 '25 04:12

user467566


1 Answers

The first block of code you show is for Vue 2, which won't work in Vue 3. And Vue 3 requires Vuex 4.

To setup Vuex 4 in a Vue 3 app:

  1. Install Vuex 4:

    npm i -S vuex@next
    
  2. Update the store to use the Vuex 4 createStore API (which creates a plugin for app.use() in the next step):

    // @/store.js
    import { createStore } from 'vuex'
    
    export default createStore({
      state: {
        userData: "USER!"
      },
      mutations: {
    
      },
      actions: {
    
      },
      getters: {
    
      }
    })
    
  3. Update the main script to install the store with app.use():

    import { createApp } from 'vue'
    import store from '@/store'
    
    const app = createApp(App)
    app.use(store)
    

demo

like image 180
tony19 Avatar answered Dec 11 '25 23:12

tony19



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!