20
2

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: computed で入力バリデーションをリアルタイム表示する

Posted at

1. この記事でやること

  • 学習アウトプットとして、computed を使って バリデーションを表示する

2. 検証環境

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

3. 結論

  • computed を使うことで、input に値を入力したタイミングで必要に応じたバリデーションを表示することができる

4. コード

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

const content = ref('')
const isValid = computed(() => content.value.length >= 5)

const errorMessage = computed(() => {
  if (content.value.length === 0) return ''
  return (isValid.value ? '' : '5文字以上入力してください')
})
</script>

<template>
  <input v-model="content" type="text">
  <p v-if="errorMessage">{{ errorMessage }}</p>
</template>

<style scoped>
  p {
    margin: 0;
    color: red;
  }
</style>
  • 入力中に 5文字未満ならエラー、未入力なら何も出さない

5. 挙動の確認

画面収録 2026-01-16 0.53.40.gif

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?