VueJoy

About

Localstorage with vue-localstorage

Local storage is a great way to store data with key/value pairs in the browser with no expiration date.

We will build a very small vueJS app using local storage that allows us to add todo item to a list. We will use a module called vue-localstorage to keep our todos even if we refresh the app.

Installation

First, let's init a project with the webpack-simple template:

vue init webpack-simple vue-localstorage-tutorial

Then inside the project, install all dependencies.

yarn install

We need to install vue-localstorage:

yarn add vue-localstorage

Setup

The next up is to setup vue-localstorage into the project in the main.js file:

import VueLocalStorage from 'vue-localstorage'
Vue.use(VueLocalStorage)

Usage

You can get rid of the existing content of the template of App.vue. Add the following markup in the App.vue, you will have a text field to write todo, with a button to add them. below that, we display all our todos.

<input type="text" v-model="text"/>
<button @click="addTodo()">Add</button>
<ul>
  <li v-for="todo in todos">
    {{ todo }}
  </li>
</ul>

Put this into the data section:

return {
  text: null,
  todos: []
}

text is used for todos text todos is a list of todo

After that, we need to create the addTodo method:

addTodo () {
  this.todos.push(this.text)
  this.text = null
  this.$localStorage.set('todos', JSON.stringify(this.todos))
}

This method add the todo to todos, then it will set null to the todo text. Finally, we will use localstorage! You can access localstorage from any component using this.$localStorage. We will use the set method to store todos, using the key todos.

We use JSON.stringify as localstorage store key and values in String.

After we add some todos, what we have on our screen is this:

local storage template

If you refresh your page, you will lost all your todos. But if you check the local storage in your browser, you will see your todos!

local storage

So what you just have to do now, it's to get todos from the local storage. Let's do this in the mounted hook.

mounted () {
  const todos = JSON.parse(this.$localStorage.get('todos'))
  if (todos) {
    this.todos = todos
  }
},

We will use this.$localStorage.get with todos as key. Don't forget to parse the string. If we have todos, they will be set to this.todos.

That's it. You have all the methods to make localstorage works!

You can find the source code on github.