When I press a button, I want to place focus on a vue input. To achieve this, I believe I need to access the HTML element by setting a ref value and using the following code:
this.$refs.theRefName.$el.focus();
However, I am encountering issues with the `refs` part of this expression. In the Minimum Reproducible Example (MRE) provided below, the `refs` object contains correct keys but empty values. Consequently, `.$el` is undefined, leading to errors.
I have read Stack Overflow articles that address situations where `this` is undefined or `$$refs` are empty due to conditional rendering, but these do not apply to my case. Why then are my `$$refs` containing 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))
// Although this is what I intend to do, I cannot proceed as 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 assist me in accessing the HTML element and giving it focus, I would greatly appreciate it.