所以我迷路了...
我有Vuex。我在文件common
中有一个模块common.js
:
const initState = {
fruits: []
}
export default {
state: initState,
mutations: {
SET_FRUITS(state, fruits) {
console.log(fruits);
state.fruits = fruits;
}
},
actions: {
async getFruits({ commit }) {
const fruits =[
{
text: 'Apple',
value: {id: 1, val: 'apple'},
},
{
text: 'Banana',
value: {id: 2, val: 'banana'},
},
{
text: 'Pear',
value: {id: 3, val: 'pear'},
},
{
text: 'Plum',
value: {id: 4, val: 'plum'},
}
];
commit('SET_FRUITS', fruits);
}
}
}
我在store
中的index.js
:
import Vue from 'vue';
import Vuex from 'vuex';
import common from './modules/common';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
common,
}
})
我尝试在App.vue中访问state.fruits:
<template>
<div>
{{ this.$store.state.fruits }}
</div>
</template>
<script>
export default {
name: 'App',
components: {
},
async mounted() {
await this.$store.dispatch('getFruits');
console.log(this.$store.state.fruits);
},
}
</script>
突变产生的 console.log
返回一系列水果。有用。这个很酷。
App.vue中console.log
中的mounted()
返回未定义。这不酷。
为什么?我想念什么?
答案 0 :(得分:0)
这是工作示例。还要仔细检查您的vuex存储配置/注册,不要忘记使用dispatch
const store = new Vuex.Store({
state: {
fruits: []
},
actions: {
getFruits({
commit
}) {
const fruits = [{
text: 'Apple',
value: {
id: 1,
val: 'apple'
},
},
{
text: 'Banana',
value: {
id: 2,
val: 'banana'
},
},
{
text: 'Pear',
value: {
id: 3,
val: 'pear'
},
},
{
text: 'Plum',
value: {
id: 4,
val: 'plum'
},
}
];
console.log(fruits)
commit('SET_FRUITS', fruits);
}
},
mutations: {
SET_FRUITS(state, fruits) {
state.fruits = fruits;
}
},
});
new Vue({
el: "#app",
store,
computed: {
fruits() {
return this.$store.state.fruits;
},
},
mounted() {
this.$store.dispatch('getFruits')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.5.1/vuex.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='app'>
<div v-for='(fruit, i) in fruits' :key="i">
{{fruit}}
</div>
</div>