I'm building a project to learn Vuex. I'm creating an array of objects in my store
like so:
Vuex Store:
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
users: [
{ id: 1, name: 'John Doe', email: '[email protected]' },
{ id: 2, name: 'Jane Doe', email: '[email protected]' },
{ id: 3, name: 'Mark Greywood', email: '[email protected]' },
]
},
mutations: {},
actions: {},
modules: {}
});
Now, I'm accesing the state
in the component with a computed property like so:
Component:
<template>
<div class="home">
<h1>Hello from Home component</h1>
<!-- I do not loop through the users, nothing shows -->
<div v-for="user in users" :key="user.id">{{ user.name }} </div>
<!-- I get the users object in the DOM -->
<div>{{ getUsers }}</div>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: "Index",
computed: mapState({
getUsers: state => state.users
})
};
</script>
<style scoped lang="less">
</style>
I don't understand what I'm doing wrong.
You don't have access to users
in this line of code
<div v-for="user in users" :key="user.id">{{ user.name }} </div>
Your component only have access to getUsers
(the computed property) which is mapped to the store object users
. Thus whenever the users
state on your store changes, getUser
also gets updated. So you should iterate on the computed property in your component.
So, the iteration should be
<div v-for="user in getUsers" :key="user.id">{{ user.name }} </div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With