44 v-for =" (number, index) in length"
55 :id =" `pin-input${number}`"
66 :key =" index"
7- : ref =" (input) => (pinInputRefs[number] = input) "
7+ ref =" inputs "
88 v-model =" innerValue[number - 1]"
99 :type =" visible ? 'text' : 'password'"
1010 maxlength =" 1"
2020</template >
2121
2222<script setup>
23- import { ref , defineProps , defineEmits , computed , watch } from ' vue' ;
23+ import { ref , defineProps , defineEmits , computed , watch , useTemplateRef } from ' vue' ;
2424
2525const props = defineProps ({
2626 modelValue: {
@@ -60,7 +60,7 @@ const props = defineProps({
6060const emits = defineEmits ([' update:modelValue' ]);
6161
6262const innerValue = ref (new Array (props .length ));
63- const pinInputRefs = ref ([] );
63+ const inputRefs = useTemplateRef ( ' inputs ' );
6464
6565const computedClass = computed (() => {
6666 let classToUse = ' ' ;
@@ -91,7 +91,7 @@ function handleInput(event, index) {
9191 const length = props .length ;
9292
9393 if (index < length && event .inputType !== ' deleteContentBackward' ) {
94- let nextInput = pinInputRefs .value [index + 1 ];
94+ let nextInput = inputRefs .value [index - 1 ];
9595 nextInput .focus ();
9696 }
9797
@@ -103,7 +103,7 @@ function handleInput(event, index) {
103103function handleBack (index ) {
104104 if (index > 1 ) {
105105 innerValue .value [index - 1 ] = ' ' ;
106- let previousInput = pinInputRefs .value [index - 1 ];
106+ let previousInput = inputRefs .value [index - 2 ];
107107
108108 setTimeout (() => {
109109 previousInput .focus ();
@@ -112,23 +112,24 @@ function handleBack(index) {
112112}
113113
114114function fixCursorPosition (index ) {
115- let input = pinInputRefs .value [index];
115+ let input = inputRefs .value [index - 1 ];
116116
117117 setTimeout (() => {
118118 input .setSelectionRange (1 , 1 );
119119 }, 3 );
120120}
121121
122122function changeInputContent (event , index ) {
123- if (event .key === ' Enter' ) {
123+ if (event .key === ' Enter' || event .charCode === 32 ) {
124+ event .preventDefault ();
124125 return ;
125126 }
126127
127128 const length = props .length ;
128129
129130 innerValue .value .splice (index - 1 , 1 , event .key );
130131 if (index < length) {
131- pinInputRefs .value [index + 1 ].focus ();
132+ inputRefs .value [index].focus ();
132133 }
133134
134135 if (index === length && innerValue .value .join (' ' ).length === length) {
0 commit comments