1

I'm working on a Vue 3 (Composition API) component where I want users to edit fields by clicking on a text element, and the corresponding input should automatically receive focus. Here's the expected behavior: A <div> displays the initial text. When the user clicks it, the <div> disappears and an <input> appears. The input must be focused at the moment it becomes visible.

Tested Solutions

  1. Using nextTick() in the editInput function

     import { ref, nextTick } from 'vue'
    
     const editing = ref(false)
     const input = ref(null)
    
     function editInput() {
       editing.value = true
       nextTick(() => {
         input.value?.focus()
       })
     }
    
  2. Using a v-focus directive with the updated hook

    export const vFocus = {
    
     updated(el, binding) {
       if (binding.value) {
         el.focus()
       }
     }
    

    }

Along with <input v-show="editing" v-focus="editing" />

Both solutions work real good, now, should I favor nextTick() or the "updated" hook ?

What are the pros/cons of each approach (performance, maintainability)?

Is there an even more “Vue-idiomatic” solution for this scenario?

Thanks

1 Answer 1

1

The answer can be found in the Vue documentation where it actually discusses using updated hook vs. nextTick (emphasis mine):

This hook is called after any DOM update of the component, which can be caused by different state changes. If you need to access the updated DOM after a specific state change, use nextTick() instead.

It'd be inefficient to check if (binding.value) every DOM update. Your use case is only for a specific state change, i.e. a corresponding <div> receiving focus, therefore nextTick() is more appropriate.

Sign up to request clarification or add additional context in comments.

1 Comment

From this perspective it totally makes sense, I am not sure what I was really thinking at the time... thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.