Search code examples
javascriptvue.jsvuexes6-modulesvuejs3

MapState not found Vuex4 with Vue3 in MVC project


In my MVC project i am using Vue3 with Vuex4 and they are working but i have got one issue with mapState.

if I use these import statements i am getting this error:

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

1 Uncaught SyntaxError: Cannot use import statement outside a module

So i add these files in my _Layout page to fix it

<script src="~/lib/vue/vue.global.js"></script>
<script src="~/lib/vuex/vuex.global.js"></script>

So far it is working. But when i want to use mapState, i am stack! not sure how to fix it,

import { mapState } from 'vuex';

I searched for mapStaate.js file but couldn't find or the files i find has just few lines of code and not working...

const store = new Vuex.Store({
state: {
    count: 0
   }
})

const homeIndex = {
data() {
    return {
    }
},
computed: mapState({
    count: state => state.count,
  })
}

Vue.createApp(homeIndex).mount("#app");

Solution

  • The import statement is for modules. You don't need the module syntax since you are loading the scripts directly. Remove the import statement and use Vuex.mapState like you used Vuex.Store:

    computed: Vuex.mapState({
       count: state => state.count,
    })
    

    If you prefer, you can use object destructuring to give a similar appearance to imports. Then you could use mapState as you did in the question:

    const { mapState, mapGetters, mapActions } = Vuex;
    
    computed: mapState({
       count: state => state.count,
    })