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文字未満ならエラー、未入力なら何も出さない
