通过脚本标签包含 vuex.js 时 Vuex mapState 引用错误

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

我是 运行 一些 Vue.js 的测试代码,并通过脚本标签包括 Vue.js、Vuex 和 javascript 文件(因为它仅用于测试目的我不想使用构建工具)。

大部分代码运行正常,但 Vuex 地图函数(mapState、mapGetters ...)无法运行。我总是得到 ReferenceError: Can't find variable: mapState。为什么我不能访问 mapState?通过脚本标签包含时不是全局函数吗?

只是一个使用 vue 文档中的代码的示例:

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])
    }
});

在我看到的许多代码示例中

import { mapState } from 'vuex'

用于允许引用 mapState。

但是正如您所说,您通过引用 Vue 和 Vuex 的脚本而不是使用构建系统来包含它们

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

在这种情况下,直接使用 "Vuex" 如下:

Vuex.mapState