728x90
예시는 vue3 에서 vuetify 를 사용중일때 년/월/일 을 차례로 입력할때 enter key 로 자료를 빠르게 등록 하고자 할때 사용하면 유용한 스크립트 이다.
<template>
<VTextField
ref="input1"
maxlength="4"
variant="underlined"
class="h-small inputNext"
@keyup.enter="focusNextInput($event)"
/>
<VTextField
ref="input2"
maxlength="4"
variant="underlined"
class="h-small inputNext"
@keyup.enter="focusNextInput($event)"
/>
<VTextField
ref="input3"
maxlength="4"
variant="underlined"
class="h-small inputNext"
@keyup.enter="focusNextInput($event)"
/>
</template>
<script setup>
import { ref } from 'vue';
function focusNextInput(event) {
// 현재 입력 필드의 다음 형제 요소를 찾음
const currentInput = event.target;
const nextInput = currentInput.nextElementSibling;
if (nextInput && nextInput.classList.contains('inputNext')) {
nextInput.focus(); // 다음 입력 필드로 포커스 이동
}
}
</script>
여러 필드가 있어도 dom 에서 그려지는 순서대로 이동하기 때문에 인덱스값 없이 함수 하나만 호출 하면 된다.
아래 예제는 maxlength 값에 따라 글자수 만큼 채워지면 다음 칸으로 이동하는 스크립트다.
<template>
<VTextField
ref="input1"
:maxlength="4"
variant="underlined"
class="h-small inputNext"
@keyup.enter="focusNextInput($event)"
@input="checkInput($event)"
/>
<VTextField
ref="input2"
:maxlength="2"
variant="underlined"
class="h-small inputNext"
@keyup.enter="focusNextInput($event)"
@input="checkInput($event)"
/>
<VTextField
ref="input3"
:maxlength="4"
variant="underlined"
class="h-small inputNext"
@keyup.enter="focusNextInput($event)"
@input="checkInput($event)"
/>
<VTextField
ref="input4"
:maxlength="3"
variant="underlined"
class="h-small inputNext"
@keyup.enter="focusNextInput($event)"
@input="checkInput($event)"
/>
</template>
<script setup>
import { ref } from 'vue';
function focusNextInput(event) {
const currentInput = event.target;
const nextInput = currentInput.nextElementSibling;
if (nextInput && nextInput.classList.contains('inputNext')) {
nextInput.focus();
}
}
function checkInput(event) {
const currentInput = event.target;
const maxLength = currentInput.getAttribute('maxlength'); // maxlength 값 가져오기
// 입력된 글자의 길이를 확인
if (currentInput.value.length >= maxLength) {
focusNextInput(event); // 다음 입력 필드로 포커스 이동
}
}
</script>
728x90
'VUE' 카테고리의 다른 글
vue3 새창으로 링크 걸기 (0) | 2024.11.16 |
---|---|
vue api 호출 에러 처리 interceptor.js 파일 예제 (0) | 2024.11.14 |
window 에서 node 버전 바꾸기 nvm (0) | 2024.05.22 |
vue v-calendar v-date-picker 년도 월 선택 팝업 추가 (0) | 2024.03.27 |
Vue.js Basic Syntax Guide: Numeric and String Conversion with Rounding Examples (0) | 2024.03.15 |