DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Top 10 Pillars of Zero Trust Networks
  • Mastering Time Series Analysis: Techniques, Models, and Strategies
  • How To Use Pandas and Matplotlib To Perform EDA In Python
  • Is Podman a Drop-in Replacement for Docker?

Trending

  • Top 10 Pillars of Zero Trust Networks
  • Mastering Time Series Analysis: Techniques, Models, and Strategies
  • How To Use Pandas and Matplotlib To Perform EDA In Python
  • Is Podman a Drop-in Replacement for Docker?
  1. DZone
  2. Data Engineering
  3. Data
  4. A Quick Intro to Vuex ORM

A Quick Intro to Vuex ORM

Learn what Vue ORM is, how it works, how it compares to Vuex, and let's get started making a scalable Vue or Nuxt application.

Anthony Gore user avatar by
Anthony Gore
CORE ·
Updated Feb. 20, 20 · Tutorial
Like (3)
Save
Tweet
Share
26.68K Views

Join the DZone community and get the full member experience.

Join For Free

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

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.

ORM tools (object-relational mapping) transform data between incompatible system using objects. ORMs are very popular for databases.

You may also like: Vue.js Tutorial 1 — Hello Vue

This allows for a significant simplification of your code. For example, rather than this.$store.state.commit("UPDATE_USER", { ... }), you can use User.update({ ... }), making your Vue code much easier to reason about.

The other advantages of Vuex ORM are that it reduces boilerplate 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.

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 to-do list example where we can mark a to-do as "done". Here's the store which will represent that:

store/index.js

Java
 




xxxxxxxxxx
1


 
1
store: {
2
  state: { todos: [] },
3
  mutations: {
4
    MARK_DONE(state, id) {
5
      const todo = state.todos.find(todo => todo.id === id);
6
      todo.done = true;
7
    }
8
  }
9
}



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

When a to-do is clicked, we'll mark it as "done" by making a commitment to the MARK_DONE mutation.

components/Home.vue

Java
 




xxxxxxxxxx
1
21


 
1
<template>
2
  <todo-item 
3
    v-for="todo in todos"
4
    :todo="todo"
5
    @click="markDone(todo.id)"
6
  />
7
</template>
8
<script>
9
  export default {
10
    computed: {
11
      todos() {
12
        return this.$store.state.todos;
13
      }
14
    },
15
    methods: {
16
      markDone(id) {
17
        this.$store.state.commit(MARK_DONE, id);
18
      }
19
    }
20
  }
21
</script> 



The Vuex ORM way

As I said, Vuex ORM represents data as models. So we'll first create a Todo model and define the fields we'd need like id, title, and done.

Unlike most Vue software, Vuex ORM uses ES6 classes for configuration.

store/models/post.js

Java
 




xxxxxxxxxx
1
14


 
1
import { Model } from "@vuex-orm/core";
2
 
          
3
export default class Todo extends Model {
4
  static entity = "todos";
5
 
          
6
  static fields () {
7
    return {
8
      id: this.string(""),      
9
      title: this.string(""),
10
      done: this.boolean(false),
11
      ...
12
    };
13
  }
14
}



Now it's time to register the model to the Vuex ORM "database", which allows you to use the model.

While we're at it, we can register the Vuex ORM plugin with Vuex.

store/index.js

Java
 




xxxxxxxxxx
1
12


 
1
 
          
2
import VuexORM from "@vuex-orm/core";
3
import Todo from "./models/Todo";
4
 
          
5
const database = new VuexORM.Database();
6
database.register(Todo, {});
7
 
          
8
const plugin = VuexORM.install(database);
9
 
          
10
export default {
11
  plugins: [plugin]
12
};



With our Vuex ORM store set up, we can start using it in our components. First, import the model into a component file. Now, rather than using the "weird" syntax of Vuex, we can use standard CRUD methods to query our store:

components/Home.vue

Java
 




xxxxxxxxxx
1
18


 
1
import Todo from "../store/models/todo";
2
export default {
3
  computed: {
4
    // posts() {
5
    //   return this.$store.state.todos;
6
    // }
7
    todos: () => Todos.all();
8
  },
9
  methods: {
10
    markAsRead(id) {
11
      // this.$store.state.commit(MARK_DONE, id);
12
      Todo.update({
13
        where: id,
14
        data: { done: true }
15
      });
16
    }
17
  }
18
}



I don't know about you, but I find that much more readable!

Store config

But hang on, where is the store configuration for the Todo model? Unless you want to customize it, you don't need any! Vuex ORM will automatically create state, mutations, and getters that are aliased to the model API e.g. read, update, find.

Plugins

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 to-do items from the server and pushes them to the store:

Java
 




xxxxxxxxxx
1


 
1
created() {
2
  try {
3
    let { data } = await this.$http.get("/todos");
4
    data.forEach(todo => this.$store.state.commit(ADD_TODO, todo));
5
  } catch (err) {
6
    // handle error
7
  }
8
}



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

Java
 




xxxxxxxxxx
1


 
1
created() {
2
  Todo.$fetch();
3
}



How easy is that?

Resources

There's plenty more to know about Vuex ORM so check out the docs:

  • Vuex ORM
  • Vuex ORM Axios plugin

Learn and master what professionals know about building, testing, and deploying, full-stack Vue apps in our latest course. Learn more


Further Reading

Vue Development in 2019: What You Need to Know

How and Why We Moved to Vue.js

Getting Your Company to Switch to Vue

Java (programming language) app application Boilerplate code Data (computing) Database Advantage (cryptography) Vue.js Web Protocols

Published at DZone with permission of Anthony Gore, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Top 10 Pillars of Zero Trust Networks
  • Mastering Time Series Analysis: Techniques, Models, and Strategies
  • How To Use Pandas and Matplotlib To Perform EDA In Python
  • Is Podman a Drop-in Replacement for Docker?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: