This must be something really basic, but I can't get it.
I have this piece of code in my <template>
:
<div v-if="this.editable">
<input type="text" ref="nota" :id="notaid" v-model="nombre" v-on:keyup.enter="enviar" v-on:blur="enviar" class="form-control">
</div>
<div v-else>
<p @click="makeEditable">{{ nombre }}</p>
</div>
So, when the page loads, editable=false
so it displays a text. When you click in the text there's a function that will make editable
true, so it displays the input. This works fine. Now, my problem is, how do I focus on the input
as soon as editable
changes to true?
I have read some articles: here , here , and some others that says I could be focusing on the element with some code as simple as:
this.$refs.nota.focus()
So makeEditable
code is:
methods: {
makeEditable() {
this.editable = true;
this.$refs.nota.focus()
},
...
Problem is, I get this error:
app.js:38487 [Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'focus' of undefined"
I'm pretty sure this is because I'm trying to focus to an element that hasn't been created yet, because if I make the same on an input
element that is always displayed, it works perfectly.
So which is the right way?
You can try Vue.nextTick(callback)
as follow:
methods: {
makeEditable() {
this.editable = true;
Vue.nextTick(() =>
this.$refs.nota.focus()
)
},
...
It tells Vue to wait until the changes are made and then call the callback.
See the documentation for more .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.