textarea
Auto-resize textarea with character count
Auto-resize textarea with character count
Загрузка превью…
src/textarea/c-textarea-6.vue
<script setup lang="ts">
import { computed, ref } from "vue"
import { Field, FieldLabel } from "@/components/ui/field"
import { Textarea } from "@/components/ui/textarea"
const MAX_CHARS = 280
const value = ref("")
function handleChange(e: Event) {
const newValue = (e.target as HTMLTextAreaElement).value
if (newValue.length <= MAX_CHARS) {
value.value = newValue
}
}
const remaining = computed(() => MAX_CHARS - value.value.length)
const isNearLimit = computed(() => remaining.value <= 20)
const isAtLimit = computed(() => remaining.value === 0)
</script>
<template>
<div class="mx-auto w-full max-w-xs">
<Field class="w-full">
<div class="flex items-center justify-between">
<FieldLabel for="auto-resize-textarea">Bio</FieldLabel>
<span
:class="`text-xs tabular-nums ${
isAtLimit
? 'text-destructive font-semibold'
: isNearLimit
? 'text-warning'
: 'text-muted-foreground'
}`"
>{{ `${value.length}/${MAX_CHARS}` }}</span>
</div>
<Textarea
id="auto-resize-textarea"
:value="value"
placeholder="Tell us about yourself..."
rows="2"
class="resize-none overflow-hidden"
@input="handleChange"
/>
</Field>
</div>
</template>