Vue.js 3 Local JSON Storage Tutorial

In this Vue tutorial we learn how to work with data stored locally in a JSON file.

We cover how to import and retrieve data from a custom local JSON file stored inside the application.

Lesson Video

If you prefer to learn visually, you can watch this lesson in video format.

Lesson Project

If you want to follow along with the examples in this lesson, you will need an app generated by the Vue CLI . If you already have one from a previous lesson, you can use it instead.

Data in a local JSON file

Vue allows us to easily access JSON data that’s stored locally on the same server as our app.

note We’re talking about reading the data only. Something like a large array, or data that’s stored in a JSON file and uploaded to the server.

Modifying files requires a node server, like express, which is outside the scope of this course, or a database like firebase, which we cover in the Firebase lesson .

As an example, let’s create a new JSON file in /src/assets/users.json .

Example: project
project_folder/
├── src/
|   ├── assets/
|   |   └── users.json
|   └── App.vue

And add the following four object literals to it.

Example: src/assets/users.json
[
  {
    "id": 0,
    "name": "John"
  },
  {
    "id": 1,
    "name": "Jane"
  },
  {
    "id": 2,
    "name": "Jack"
  },
  {
    "id": 3,
    "name": "Jill"
  }
]

How to get data from a local JSON file

To get data from a local JSON file, we need to import the file into the component where we want to process the data.

We do the import just like we would with a component, except the component name is replaced with whatever we want to call the data set.

Example: import JSON
<script>
import userData from './assets/users.json'
</script>

tip A good way to avoid naming conflicts with component imports is to use camelCase for the name. For example: userData instead of UserData .

Once the file is imported, we can assign it to a data property and then use the data property however we want, like looping through it to display the names in the template block.

Example: src/App.vue
<template>
  <p v-for="user in users" :key="user.id">
    {{user.name}}
  </p>
</template>

<script>
import userData from './assets/users.json'

export default {
  data() {
    return {
      users: userData,
    };
  },
};
</script>

If we save the file and take a look in the browser, all 4 names should show on the page.

Further Reading

For more information on the topics covered in this lesson, please see the relevant sections below.