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

Mou*_*ain 3 javascript vue.js vuex vuejs2

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

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

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

索引.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>
Run Code Online (Sandbox Code Playgroud)

商店.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
})
Run Code Online (Sandbox Code Playgroud)

应用程序.js

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

Luk*_*uke 7

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

import { mapState } from 'vuex'
Run Code Online (Sandbox Code Playgroud)

用于允许引用 mapState。

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

<script src="vendor/js/vue.js" type="text/javascript"></script>
<script src="vendor/js/vuex.js" type="text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)

在这种情况下,直接使用“Vuex”,如下所示:

Vuex.mapState
Run Code Online (Sandbox Code Playgroud)