In one of my components I’ve got a form that changes form depending on the value of a radio button.
My component looks like this:
<template>
<div>
<div>
<label>
<input
class="radio"
name="groupInput"
type="radio"
value="one"
v-model="groupActive"
/>
Group 1
</label>
<label>
<input
class="radio"
name="groupInput"
type="radio"
value="two"
v-model="groupActive"
/>
Group 2
</label>
</div>
<input v-if="groupActive === 'one'" type="text" ref="defaultInput" />
<select v-else ref="defaultInput">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
</div>
</template>
<script setup>
import { ref, onMounted } from "vue";
const groupActive = ref("one");
const defaultInput = ref(null);
onMounted(() => {
defaultInput.value.focus();
});
</script>
When the component is mounted, defaultInput is focused. But when I change the value of the radio button, the <input> I was focusing on is no longer available and I’d like to focus on the new . How can I achieve this? Is it possible to update the ref value to the new <select> and then focus on it?
>Solution :
You can use onUpdated as well to handle reactive state changes after the initial mount.
<script setup>
import { ref, onMounted, onUpdated } from "vue";
const groupActive = ref("one");
const defaultInput = ref(null);
const focusInput = () => defaultInput.value.focus();
onMounted(focusInput);
onUpdated(focusInput);
</script>