2👍
Would this approach work? Here I’m deferring this.$refs.textInput.focus()
to be executed after the next DOM update cycle (thanks @Bert for reminding) so that Vue could re-render the component (i.e. it adds the input and sets the ref) and we would have the ref to call focus()
function.
new Vue({
el: "#app",
data: {
x: 1,
text: 'Hey'
},
methods: {
toggle: function(todo){
todo.done = !todo.done
}
},
mounted() {
setInterval(() => {
this.x = 1 - this.x;
}, 1000);
},
watch: {
x: {
handler: function(value) {
this.$nextTick(() => {
this.$refs.textInput && this.$refs.textInput.focus();
});
}
}
}
})
body {
padding: 20px;
}
#app {
background: powderblue;
padding: 20px;
}
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<div v-if="x===0">
<input ref="textInput" v-model="text">
</div>
</div>
0👍
Would autofocus work?
<div v-if="x===0">
<input ref="text" autofocus>{{text}}</input>
</div>
Source:stackexchange.com