Vue Form With Local Storage

Learn how to create a form with local storage using VueUse in Vue and Nuxt applications.

The VueUse library along with Vue and Nuxt make creating forms with local storage easy. This article will show you how to create a form with local storage using VueUse.

The following pattern will work with both a SPA Vue application and a server rendered Nuxt application. When the user enters data in the form it will be reactively saved in local storage.

<script setup>
  import { useStorage } from '@vueuse/core'

  const form = useStorage('form-name-key', {
    name: '',
    email: '',
  })
</script>

<template>
  <form>
    <input v-model="form.name" type="text" />
    <input v-model="form.email" type="text" />
  </form>
</template>

This is a simple example but in a more complex case where you have a big or multistep form and your user closes the tab or window accidentally you will save them a lot of time and frustration.

A note about server side rendering with Nuxt. When the component is rendered on the server it doesn't have access to the browsers local storage so all the values are empty. When the component is run in the browser after the initial render it has access to local storage and populates the inputs. This results in a Hydration attribute mismatch console warning from Vue. The Vue 3.5 release added the data-allow-mismatch attribute to suppress hydration mismatch warnings for this type of senario.