Home > database >  How to set focus on input inside of v-if/v-else?
How to set focus on input inside of v-if/v-else?

Time:08-03

I have an inline edit I'm working on, and when the input is active I want to set the focus on it. I think the issue though, is that it's within a v-if/v-else so the ref isn't being properly set.

I currently get this error:

Uncaught (in promise) TypeError: Cannot read properties of null (reading 'focus')

Relevant code:

<template>
  <SlideUpTransition>
    <q-btn
      v-if="!isAdding"
      flat
      
      color="primary"
      :ripple="false"
      label="  Create New Answer"
      @keydown="toggleIsAdding(true)"
      @click="toggleIsAdding(true)" />
    <q-input
      v-else
      ref="target"
      v-model="newAnswer"
      v-on-click-outside="() => toggleIsAdding(false)"
      
      label="New Answer"
      outlined
      dense
      @keyup.escape="handleEscape"
      @keyup.enter="handleSubmitAnswer"
      @keyup.tab="handleSubmitAnswer"
      @blur="handleSubmitAnswer">
      <template #append>
        <q-btn
          icon="bi-check-circle"
          flat
          :ripple="false"
          color="primary"
          @click="handleSubmitAnswer" />
      </template>
    </q-input>
  </SlideUpTransition>
</template>

<script lang="ts" setup>
  import { computed, ref, nextTick } from 'vue';
  import { vOnClickOutside } from '@vueuse/components';
  import SlideUpTransition from '@/components/transitions/SlideUpTransition.vue';

  const isAdding = ref(false);
  const target = ref<any>(null);
  const newAnswer = ref('');

  const toggleIsAdding = (val: boolean) => {
    isAdding.value = val;
    if (isAdding.value) {
      nextTick(() => {
        target.value.focus(); // <-- target.value is still null
      });
    }
  };
</script

Is there a better way to handle focusing an input that isn't part of the DOM yet?

CodePudding user response:

Since you are using quasar, I think the best way is to use either QInput's autofocus property, or QForm's autofocus.

Personally, I usually wrap a QInput in a QForm, and set autofocus on the input that I want to be focused. The added benefit is that you don't need to listen to @keyup.enter, but can instead use the form's @submit event (a little bit of future-proofing if you also add a submit button).

  • Related