<script lang="ts" setup> import { ref, computed } from 'vue' const { modelValue = '' } = defineProps<{ modelValue: string }>() const emit = defineEmits(['update:modelValue']) const isFilled = ref(false) const value = computed({ get() { return modelValue }, set(value: string) { isFilled.value = value.length > 0 emit('update:modelValue', value) } }) </script> <template> <input v-model="value" :class="{ 'filled': isFilled }" v-bind="$attrs" /> </template>Esto no tendrá efecto cuando se presione la tecla por primera vez. Por ejemplo: presione abcdefg, el último cuadro de entrada muestra bcdefg, elimínelo con la tecla de retroceso e intente nuevamente, sigue siendo el mismo.
isFilled.value = value.length > 0 y funciona bien, pero de lo contrario, ¿cómo puedo agregar una clase al elemento?
El efecto que necesito es agregarle una clase llamada llena cuando el valor del cuadro de entrada no está vacío.
Habría usado un observador para esta tarea, código de ejemplo:
<script lang="ts" setup> import { ref, watch } from 'vue' const { modelValue = '' } = defineProps<{ modelValue: string }>() const emit = defineEmits(['update:modelValue']) const isFilled = ref(false) const inputText = ref("") watch(inputText,(newValue, oldValue)=>{ isFilled.value = inputText.value.length > 0 emit('update:modelValue', inputText.value) }) </script> <template> <input v-model="inputText" :class="{ 'filled': isFilled }" v-bind="$attrs" /> </template>Si solo desea agregar la clase, también puede hacerlo en línea. ejemplo:
<script lang="ts" setup> import { ref, watch } from 'vue' const inputText = ref("") </script> <template> <input v-model="inputText" :class="{ 'filled': (inputText.length>0) }" v-bind="$attrs" /> </template>