11
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vue 3:watch を使って localStorage へ保存する

Posted at

1. この記事でやること

  • 学習アウトプットとして、watch を使って localStorage へ保存する

2. 検証環境

  • Vue 3.4.35
  • Nuxt 3.12.4
  • Node v22.20.0
  • Yarn 1.22.18
  • macOS Sequoia 15.6

3. 結論

  • watch を使うことで、input に値を入力したタイミングで localStorage へ自動保存できる

4. コード

SampleView.vue
<script setup>
import { ref, watch } from 'vue'

const currentText = ref('')
const storedText = ref('')

const STORAGE_KEY_INPUT_TEXT = 'inputText'

watch(currentText, (newValue) => {
  localStorage.setItem(STORAGE_KEY_INPUT_TEXT, newValue)

  // 保存できたか確認のため、あえて読み直して表示する
  storedText.value = localStorage.getItem(STORAGE_KEY_INPUT_TEXT) ?? ''
})
</script>

<template>
  localStorageに保存:<input v-model="currentText" type="text" /><br />
  localStorageの中身:{{ storedText }}
</template>
  • watch のコールバック内で、副作用(localStorage への保存)を実行する
  • 今回は「保存できたことが目で分かる」ように、あえて getItem() で読み直して storedText に表示している

5. 挙動の確認

watch.gif

  • input に文字を入力すると、watch が発火して localStorage の値が即時に更新されることが確認できる
11
0
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
11
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?