'How to setFocus on Next button press event in Ionic-vue app?
I’m having difficulties trying to change focus from one input to another by pressing the next button in android/ios keyboard since there is no example for the usage of setFocus method.
Maybe somebody here has already achieved this before? Can anyone please show me some example?
What I’ve tried so far:
Form.vue
<template>
<form @submit.prevent="onSubmit">
<form-input
enterkeyhint="next"
v-model="email"
@keyup.enter="changeFocus('password')"
/>
<form-input
ref="password"
v-model="password"
/>
</form>
</template>
<script lang="ts">
// ... some import statements
export default defineComponent({
setup() {
const email = ref("");
const password = ref("");
return {
email,
password,
};
},
methods: {
changeFocus(nextFocus: string): void {
this.$refs[nextFocus].setFocus();
},
},
});
</script>
errors
TS2571: Object is of type 'unknown'.
[vue-cli-service] 80 | methods: {
[vue-cli-service] 81 | changeFocus(nextFocus: string): void {
[vue-cli-service] > 82 | this.$refs[nextFocus].setFocus();
[vue-cli-service] | ^^^^^^^^^^^^^^^^^^^^^
[vue-cli-service] 83 | },
[vue-cli-service] 84 | },
[vue-cli-service] 85 | });
Solution 1:[1]
You could use ref template by defining it as property and use inside a event handler :
<template>
<form @submit.prevent="onSubmit">
<form-input
enterkeyhint="next"
@keyup.enter="changeFocus('password')"
/>
<form-input
ref="password"
/>
</form>
</template>
<script lang="ts">
// ... some import statements
export default defineComponent({
setup() {
const password=ref<string>("")
function changeFocus(nextFocus: string): void {
password.value.focus()
}
return{
changeFocus, password,email
}
},
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | luckydonald |