Home > Software engineering >  Get an element by its ref in vue and give it focus
Get an element by its ref in vue and give it focus

Time:08-09

I'd like to give focus to a vue input when a button is pressed. My understanding is that I need the html element, which I get by setting a ref value, then saying:

this.$refs.theRefName.$el.focus();

But I'm getting tripped up on the refs part of that expression. See the MRE below where refs contains the correct keys, but the values are empty. As a result .$el is undefined and the expression errs.

I've seen SO articles that deal with this being undefined (not a problem for me) or $refs being empty because the element was conditionally rendered (also, not a problem for me). I've got $refs, but why does it contain empty objects?

Vue.config.productionTip = false;
Vue.config.devtools = false;

var app = new Vue({
  el: '#app',
  data: {
    message: 'World'
  },
  methods: {
    click() {
      alert(JSON.stringify(this.$refs))
      // here's what I want to do, but I can't because inp2 is empty
      // this.$refs.inp2.$el.focus();
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h1>Why are refs empty objects?</h1>
  <input ref="inp1"></input><br/><br/>
  <input ref="inp2" placeholder="i want focus on click"></input><br/><br/>
  <button @click="click">Click me</button>
</div>

If you can help me get to the html element and give it focus, I'd be much obliged.

CodePudding user response:

Try without $el :

Vue.config.productionTip = false;
Vue.config.devtools = false;

var app = new Vue({
  el: '#app',
  data: {
    message: 'World'
  },
  methods: {
    click() {
      this.$refs.inp2.focus();
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue-icons.min.js"></script>
<div id="app">
  <h1>Why are refs empty objects?</h1>
  <input ref="inp1" /><br/><br/>
  <b-form-input ref="inp2" placeholder="i want focus on click"></b-form-input>
  <button @click="click">Click me</button>
</div>

  • Related