Skip to content

Elements lose focus on re-render when siblings use v-if, even if element is reused #9883

@adamwathan

Description

@adamwathan

Version

2.6.10

Reproduction link

https://codepen.io/anon/pen/ZZvVWv

Steps to reproduce

Create a component that contains a button or input sandwiched in between two other elements that are both conditionally rendered using v-if against the same piece of data:

new Vue({
  el: '#app',
  template: `
  <div id="app">
    <div v-if="open">Hello</div>
    <input key="input" ref="input" @focus="open = true" @blur="open = false">
    <div v-if="open">World</div>
  </div>
  `,
  data: {
    open: false
  }
)

Now click the input to try and focus it.

What is expected?

The two conditional elements appear, the input is focused.

What is actually happening?

The input is focused but immediately blurred, the component renders twice, and the conditional elements are hidden. It is impossible to actually focus the input. This is bizarre because the element is the exact same DOM node, you can confirm via logging, and that's what key is there to ensure.


This example looks silly but it's a real problem when you start trying to build things like autocomplete components, where you want to render an invisible clickable backdrop to add simple "click away" behavior (this is how GitHub does click away, it's the only bullet proof approach I've found especially when you start using portals as well) and you also need to render the autocomplete dropdown when the input is focused.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions