1
2

Vue 3で簡単にlocalStorageを使う方法

Last updated at Posted at 2023-03-06

結論

VueUseのuseStorageを使う。

npm i @vueuse/core
const storedValue = useStorage('key', value)

詳細

VueUseとは、Vue 3のComposition APIをベースにしたユーティリティ関数のコレクションです。
その中にuseStorageというユーティリティがあるので、Vue 3でlocalStorageを扱いたい場合はこちらを使用すると良いでしょう。

インストール

  • パッケージマネージャでインストールする場合

    npm i @vueuse/core
    
  • CDNでインストールする場合

    <script src="https://unpkg.com/@vueuse/core"></script>
    

window.VueUseとして公開されます。

使用法

useStorage()は第1引数に参照に用いるキー名を、第2引数に保存する値を渡します。

const storedValue = useStorage('key', value) 

1. 値の保存と取得

便利なことに、localStorageでは値の保存setItem()と取得getItem()は別々のメソッドが担っていましたが、useStorage()はこれ1つで保存と取得を行えます。
具体的には、上記のように書いた場合

  • localStorageから'key'を探索する
    • 'key'が存在すればその値をstoredValueに代入する
    • 存在しなければvalueをキー名'key'localStorageに保存する

という処理が行われます。
また、useStorage()の戻り値はリアクティブなRef<typeof keyValue>となるので、<template>セクションではそのままアクセスでき、<script>セクション内では.valueでアンラップする必要があります。

2. 値の削除

localStorageの削除removeItem()は、nullの代入で行えます。

storedValue.value = null

デモ

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

  const msg = useStorage('msg', 'Hello World!')

  function clear() {
    msg.value = null
  }
</script>

<template>
  <textarea v-model="msg"></textarea>
  <br />
  <button @click="clear">clear</button>
</template>

テキストエリアのテキストを編集して画面をリロードしても、編集した状態が保存されていることがわかります。
clearボタンを押すとlocalStorageに保存された値がクリアされるので、再度リロードすると初期表示Hello World!に戻ります。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2