Vuex-ORM

João Nascimento
4 min readFeb 15, 2021

Vuex-orm is a plugin for Vuex to enable Object-Relational Mapping.

V uex ORM lets you create “normalized” data schema within Vuex Store with relationships such as “Has One” and “Belongs To Many” like any other usual ORM library. It also provides fluent API to get, search and update Store state.

If you’re looking to make a scalable Vue app, you might like using Vuex ORM. I’ve recently used it in a project, I’ll share with you how it works and why I think you’ll like it too

It is very similar to Laravel eloquent queries, for who are familiar to, it its even easy for them.

What is Vuex ORM

Vuex introduces some powerful concepts for managing your application state including the store, mutations, actions, and so on.

Vuex ORM is an abstraction of Vuex that allows you to think about your application state in terms of models e.g. Posts, Users, Orders, etc, and CRUD operations, e.g. create, update, delete, etc.

This allows for a significant simplification of your code. The other advantages of Vuex ORM are that it reduces code by setting up the mutations and getter you’ll need automatically, and also makes it easy to work with nested data structures in your application state.

Moving from Vuex to Vuex ORM

As a way of demonstrating the advantages, let’s refactor some raw Vuex code using Vuex ORM.

We’ll use a classic product list, where we can add quantity. Here’s the store which will represent that:

store/product.js

Let’s say we display our to-do items on the home page of the app. We’ll use a computed property products and a v-for to link the products items to the template.

When a add product is clicked, we’ll add a product to the list by making a commit to the QuantityAdd mutation.

components/Home.vue

I find that much more readable and easy!

Store config

Vuex ORM will automatically create state, mutations, and getters that are aliased to the model API e.g. read, update, find, create, etc

Plugins (must install)

Vuex ORM Axios — Is a plugin to sync the store against a RESTful API.

Even better, you can add some really handy plugins to Vuex ORM (that’s right, a plugin for a plugin for a plugin), include ones to abstract your server communication.

For example, there is an Axios plugin that is almost zero config so long as your model endpoints fit the RESTful pattern.

Let’s say when our app loads, it retrieves all the Products items from the server and pushes them to the store:

The Vuex ORM Axios plugin adds additional model methods like fetch which allows you to replace the above code with:

Compare laravel queries with Vuex-ORM

In vuex-ORM you can make queries like in Laravel, here is an example of it, using the whereHas…

Like in the Laravel

How easy is that ? And all the reduced code made… Amazing tool

--

--