gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:21:44 26 4
gpt4 key购买 nike

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

大部分代码运行正常,但 Vuex map 函数(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>

商店.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
})

应用程序.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

关于javascript - 通过脚本标签包含 vuex.js 时 Vuex mapState 引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48747649/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com