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 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

An application may not always need a large external storage solution like Firebase .

If our application is small and doesn’t need a lot of data, or if we simply want to work with a large array, we can use a JSON file that’s stored locally on the same server as our app.

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.