In this example, we’ll see how we can limit the length of text input (characters) using temporary states.
Here’s the code example:
<script setup>
import { ref } from 'vue'
const inputText = ref('')
const tempText = ref('')
const enterInputValue = (e) => {
if(tempText.value.length <= 10) {
inputText.value = tempText.value
}
}
</script>
<template>
<div>
<h2>
Enter name:
</h2>
<input v-model="tempText" type="text" @keyup="enterInputValue($event)"/>
<p>
Entered name: {{ inputText }}
</p>
</div>
</template>
Code language: HTML, XML (xml)
In the above code, we’ve declared two reactive states named inputText and tempText. We also have a method on line 7 that copies the value of tempText to inputText only if the entered length of tempText is less than or equal to 10.
We bind the enterInputValue method with the @keyup event listener of the input field on line 18.
Then on line 20, we print the actual valid value of the inputText state.
You can find a working version of the above code from my repo links below: