I have a Vue.js app. This app is using Vuex for state management. My store looks like this:
const store = new Vuex.Store({
state: {
items: []
},
mutations: {
MUTATE_ITEMS: (state, items) => {
state.items = items;
}
},
actions: {
loadItems: (context, items) => {
context.commit('MUTATE_ITEMS', items);
}
}
})
;
In my Vue instance, I have the following method:
loadItems() {
let items = [];
for (let I=0; I<10; I++) {
items.push({ id:(I+1), name: 'Item #' + (I+1) });
}
this.$store.dispatch('loadItems', items);
},
When I run this, I notice that the item list in my child components are not getting updated. I suspect this is because of the reactivity model in Vue.js. However, I'm not sure how to update an entire array. In addition, I'm not sure if I need to use Vue.set
in my store mutation, store action, or in the Vue instance method itself. I'm slightly confused.
Component:
<template>
<div>
<h1>Items ({{ items.length }})</h1>
<table>
<tbody>
<tr v-for="item in items" :key="item.id">
<td>{{ item.id }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import { mapState } from 'vuex';
export default {
computed: mapState({
items: state => state.items
})
};
</script>
How do I update an entire Array that is centrally stored in Vuex in a Vue.js app?
require
statements. I feel like its so close. I'm just not sure what I'm doing wrong. – Indopacificrequire
you can useimport
in your router (you can check this post to see the difference) : fixed codeSandbox – Twilatwilight