Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change ref element when element isn't visible anymore?

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>

Here’s a working example.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading