1👍
Usually, we have e.g. a span
before editing, and would use v-show
rather than v-if
on it since we still need it after editing, and each input
is coupled with its according span
, so something like event.target.nextSibling.focus()
will do the job.
I prefer event.target...
to $refs
as declaring $refs
adds complexity to the component’s structure while the other is just something only relevant within the click event.
1👍
If you really wanted to avoid the use of vanilla js (apart from for focusing) then I’d suggest you have to move your list elements into a component:
Vue.component('list-items', {
template:
`<div>
<button @click="edit">edit</button>
<input v-if="editing" ref="input" type="text" :value="value" @input="$emit('input', $event.target.value)">
</div>`,
props: ['value'],
data () {
return {
editing: false,
}
},
methods: {
edit () {
this.editing = !this.editing
if (this.editing) {
this.$nextTick(() => {
this.$refs.input.focus()
})
}
},
},
})
new Vue({
el: '#app',
data: {
list: [{
title: 'foo',
}, {
title: 'bar',
}]
},
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<list-items v-model="item.title" v-for="item in list"></list-items>
<pre>{{ list }}</pre>
</div>
👤GuyC
Source:stackexchange.com