The solution, ofcourse, is Vuex. Vuex is a state management library for Vue.js applications. At the center of every Vuex application is a store, which basically is a container that holds the state of the application.
In this article I will show you how to setup a Vuex store and how you can use this store within the Vue components. I will be starting from scratch with a new Vue project.
index.js is where the state of the module gets defined. Furthermore, this file bundles the getters, actions and mutations into an object that represents the module.
I prefer my modules to being namespaced. By default, everything inside a module is registered under the global namespace. This allows multiple modules to react to the same mutation or action. I don’t like this default behaviour, so I chose for namespaced = true; in the modules. This way the modules are more self-contained.
In this example we have two actions that both commit a mutation. The addProducts action commits the addProduct mutation, which we will use later on.
In the example that we are going to create we won’t be using the getProducts action. I created this action as an extra (asynchronous) example of what an action can look like. The getProducts action sends a request to an API and commits a mutation based on the response.
getters.js contains all the getter functions. Getters are for a store what computed properties are for a component. Getters have access to the state aswell, via the first parameter.
The ProductList component contains a list of all products, both in stock and not in stock. The list will only be displayed if the list of products is not empty.
Note that the products variable is coming from the state object. We use the mapState helper for this. This helper generates computed getter functions for us.
Since we namespaced the module we need to pass the name of the module as the first argument. The second argument is the list of properties that we want to create the getter functions for.
We use the spread operator (…) so that we are able to mix local computed properties with the object that mapState returns.