Mountain
Mountain

Reputation: 1059

Vuex mapState reference error when vuex.js is included via script tag

I'm running some test code for Vue.js and include Vue.js, Vuex and the javascript files via script tags (because it is for testing purposes only I don't want to use a build tool).

Most of the code runs correctly but the Vuex map functions (mapState, mapGetters ...) won't work. I always get ReferenceError: Can't find variable: mapState. Why can't I access the mapState? Aren't that global functions when included via script tag?

Just an example using code from the vue docs:

index.html

<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />

    <title></title>
</head>


<body>

    <div id="app"></div>


    <!-- Libraries ---------- -->
    <script src="vendor/js/vue.js" type="text/javascript"></script>
    <script src="vendor/js/vuex.js" type="text/javascript"></script>

    <script src="app/js/store.js" type="text/javascript"></script>
    <script src="app/js/app.js" type="text/javascript"></script>

</body>

</html>

store.js

const state = {
    count: 0
}


const getters = {
    evenOrOdd: state => state.count % 2 === 0 ? 'even' : 'odd'
}


const mutations = {
    increment (state) {
        state.count++
    },
    decrement (state) {
        state.count--
    }
}


const actions = {
    increment: ({ commit }) => commit('increment'),
    decrement: ({ commit }) => commit('decrement'),
    incrementIfOdd: ({ commit, state }) => {
        if ((state.count + 1) % 2 === 0) {
            commit('increment')
        }
    },
    incrementAsync: ({ commit }) => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                commit('increment')
                resolve()
            }, 1000)
        })
    }
}


const store = new Vuex.Store({
    state,
    getters,
    mutations,
    actions
})

app.js

const app = new Vue({
    el: '#app',
    template: `
        <main>
            <h1 class="title">Heading</h1>
        </main>
    `,
    store,
    computed: {
        ...mapState([count])
    }
});

Upvotes: 3

Views: 3260

Answers (1)

Luke
Luke

Reputation: 1258

In Many code examples I see

import { mapState } from 'vuex'

used to allow mapState to be referenced.

But as you say, you are including Vue and Vuex by referencing their scripts instead of using a build system

<script src="vendor/js/vue.js" type="text/javascript"></script>
<script src="vendor/js/vuex.js" type="text/javascript"></script>

And in this case, directly using "Vuex" as below works:

Vuex.mapState

Upvotes: 7

Related Questions