Episode 3 of 8
Setting up a Central Store
Install Vuex and create a central store — move your application's shared state into a single, accessible location.
Setting up a Central Store
Now let us add Vuex and move the shared state into a central store that all components can access directly — no more passing data through intermediary components.
Installing Vuex
npm install vuex
Creating the Store
// src/store/store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
products: [
{ id: 1, name: 'Banana Skin', price: 20 },
{ id: 2, name: 'Shiny Star', price: 40 },
{ id: 3, name: 'Green Shells', price: 60 },
{ id: 4, name: 'Red Shells', price: 80 },
{ id: 5, name: 'Mushroom', price: 15 }
]
}
});
Registering the Store
// src/main.js
import Vue from 'vue';
import App from './App.vue';
import { store } from './store/store';
new Vue({
store,
render: h => h(App),
}).$mount('#app');
Passing store to the root Vue instance makes it available in every component as this.$store.
Accessing State in Components
<!-- ProductList.vue — no more props needed! -->
<template>
<div class="product-list">
<div v-for="product in products" :key="product.id" class="product">
<span>{{ product.name }} — ${{ product.price }}</span>
</div>
</div>
</template>
<script>
export default {
computed: {
products() {
return this.$store.state.products;
}
}
};
</script>
Instead of receiving products via a prop from the parent, the component reads directly from the store using this.$store.state.products. Any component in the tree can do this.
Store Structure
| Property | Purpose |
|---|---|
state | The reactive data object — the single source of truth |
getters | Computed properties for the store (episode 5) |
mutations | Synchronous functions that change state (episode 6) |
actions | Asynchronous functions that commit mutations (episode 7) |
Before vs After Vuex
Before: App.vue passes products as a prop → ProductList.vue
After: ProductList.vue reads directly from store.state.products
Key Takeaways
new Vuex.Store({ state })creates a central store- Inject it into the root Vue instance to make
this.$storeavailable globally - Access state in components with
this.$store.state.propertyName - Use computed properties to keep the template reactive to store changes
- Components no longer need props for shared data — they read from the store directly