I have a Vue.js app. In this app, I have an array of items that I want to use in multiple single file components. This array may be fairly large. For that reason, I'm trying to reduce instances of the array in memory.
Since I intend to share this array across components, I thought a centralized store made sense. For this reason, I started to integrate Vuex.
In my app, I have the following:
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
contacts: [
// large number of JSON objects here.
]
}
});
const app = new Vue({
store,
el: '#myApp',
data: {},
created: function() {
}
});
I have a single file component that looks like this:
<template>
<div>
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
<thead>
<tbody>
<tr v-for="contact in contacts">
<td>{{ contact.firstName }}</td>
<td>{{ contact.lastName }} </td>
<td>{{ contact.email }} </td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data: function() {
return {};
}
};
</script>
In reality, I have multiple single file components that will need to use contacts
from the store
. However, I'm not sure what the most efficient way to use them in each component. Since each component has it's own isolated scope, it seems like if I use the props
or data
options, I'd be recreating my contacts
Array for each component. This seems expensive. Or, I'm misunderstanding something.
What is the most efficient way to share an Array with multiple components when I already have defined it in a central data store?
Thank you!
The typical approach is to use the mapState
helper in your component. For example
import { mapState } from 'vuex'
export default {
computed: mapState(['contacts'])
}
This will map the contacts
state in your store into a computed property contacts
in your component.