Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, and it makes them easily testable by taking advantage of functional composition. This post discusses how to use it with Vue.js.
Vuex is a single state object store that defines and retrieves the original state as well as the behavior to be repeated (from previous calls to the store) in response to user interactions, such as navigation, changes in a state object, or even changes in the current Vue instance. The stores can also be composed.
It also helps for client-side data fetching by using Vuex. fetch and components. The bundle.js entry point in Vue can also accept a native Vuex object as a second argument (as opposed to strings as inputs, but that’s just an example).
At its core, Vuex is a simple functional abstraction layer on top of an object-oriented event-driven architecture. Its interaction with native DOM lifecycle methods, like onload and remove EventListener, is a fairly straightforward manipulation of native DOM events and properties.
This makes Vuex especially useful in scenarios where your data is managed in a data store, but your API is cloud-based or mobile-oriented, or even calls multiple data stores. Vuex allows you to remove any single point of failure that leads to slowdowns or inconsistent data as it is used by various components.
What makes Vuex really special is its scope. The most common Vuex actions you will use are:
Vuex also provides small utility methods you might not immediately think of that allow you to fetch any error or token from your REST API as well as create a persistent store, parse/transform the text of your response and use it in your application as JSON, XML or any other required format.
What is the abstraction layer?
Most of the Vuex actions come from vue-fs , but I also added Vuex Actions and Vuex Services. Vuex Actions are created and supported by the actual endpoints and for the most part they all have exactly the same semantics. Some of the additions from Vuex Actions include:
- Running a specific action against a route on the server-side
- Executing a code block for each iteration
- Rebinding a key to a property on an instance when not used
- Creating a jQuery file of the scope with the route’s IDs and current script file
- Invoking a method on an instance from your client-side script
Loosely wrapping up this section, running an action on the server-side for a specific route is slightly different to the client side. Rather than running a function in the server, we simply use $on and $emit with a server-side function.
You’ll need to know the server-side routeId or the route name so you can find the route for your user’s name in your user controller.
We’re also running the ‘show’ action in our tusetap-api route for this server-side event.