Intentando enfocar automáticamente en el siguiente campo de entrada después de escribir 1 carácter.
Obteniendo error: la propiedad '$ refs' no existe en el tipo 'void'.
Aquí está la función:
setup() { const autoFocusNextInput = (event, max: number) => { if (event.target.value.length === max) { const nextElement = this.$refs[`input-${Number(event.target.dataset.index) + 1}`]; if (nextElement) nextElement.focus(); } };Aquí está la plantilla para el contexto:
<div class="d-flex flex-wrap justify-content-between"> <Field class= type="text" name="1" maxlength="1" ref="input-0" data-index="0" @input="autoFocusNextInput($event, 1)" autocomplete="off" /> <Field class= type="text" name="2" maxlength="1" ref="input-1" data-index="1" @input="autoFocusNextInput($event, 1)" autocomplete="off" />El problema está en la sintaxis de la función de flecha. La función de flecha no define su propio contexto de ejecución. this valor dentro de una función de flecha siempre es igual a this valor de la función exterior.
Vue vinculará this palabra clave a la instancia para que siempre haga referencia a la instancia del componente. Debido a esto, es realmente necesario no usar funciones de flecha al definir métodos porque siempre vinculan this al contexto principal, que en realidad no es la instancia de Vue, sino el objeto global ( the Window ).
Demostración de trabajo con sintaxis de función regular:
new Vue({ el:'#app', methods: { autoFocusNextInput(event, max) { if (event.target.value.length === max) { const nextElement = this.$refs[`input-${Number(event.target.dataset.index) + 1}`]; if (nextElement) nextElement.focus(); } } } }) <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id='app'> <input type="text" name="1" maxlength="1" ref="input-0" data-index="0" @input="autoFocusNextInput($event, 1)" autocomplete="off" /> <input type="text" name="2" maxlength="1" ref="input-1" data-index="1" @input="autoFocusNextInput($event, 1)" autocomplete="off" /> </div>Mi enfoque Vue3 para eliminar .this palabra clave.
const autoFocusNextInput = (event) => { if (event.target.value.length === 1) { const nextInput = event.target.nextElementSibling; if (nextInput) { nextInput.focus(); } else { event.target.blur(); } } }; <Field class="" type="text" name="input1" maxlength="1" @input="autoFocusNextInput($event)" autocomplete="off" autofocus /> <Field class="" type="text" name="input2" maxlength="1" @input="autoFocusNextInput($event)" autocomplete="off" />