I’m looking for a click-and-edit Vue component.
I’ve found a fiddle and made some edits. It works like this:
The problem: I need an additional click to make the input focused. How can I make it focused automatically?
The code from the fiddle. HTML:
JavaScript
x
16
16
1
<div id="app">
2
Click the values to edit!
3
<ul class="todo-list">
4
<li v-for = "todo in todos">
5
<input v-if = "todo.edit" v-model = "todo.title"
6
@blur= "todo.edit = false; $emit('update')"
7
@keyup.enter = "todo.edit=false; $emit('update')">
8
<div v-else>
9
<label @click = "todo.edit = true;"> {{todo.title}} </label>
10
</div>
11
</li>
12
</ul>
13
14
15
</div>
16
JS:
JavaScript
1
17
17
1
new Vue({
2
el: '#app',
3
data: {
4
todos: [{'title':'one value','edit':false},
5
{'title':'one value','edit':false},
6
{'title':'otro titulo','edit':false}],
7
editedTodo: null,
8
message: 'Hello Vue.js!'
9
},
10
methods: {
11
editTodo: function(todo) {
12
this.editedTodo = todo;
13
},
14
}
15
16
})
17
Advertisement
Answer
You can use a directive, for example
JS
JavaScript
1
25
25
1
new Vue({
2
el: '#app',
3
data: {
4
todos: [
5
{ title: 'one value', edit: false },
6
{ title: 'one value', edit: false },
7
{ title: 'otro titulo', edit: false }
8
],
9
editedTodo: null,
10
message: 'Hello Vue.js!'
11
},
12
methods: {
13
editTodo: function (todo) {
14
this.editedTodo = todo
15
}
16
},
17
directives: {
18
focus: {
19
inserted (el) {
20
el.focus()
21
}
22
}
23
}
24
})
25
HTML
JavaScript
1
18
18
1
<div id="app">
2
Click the values to edit!
3
<ul class="todo-list">
4
<li v-for="todo in todos">
5
<input
6
v-if="todo.edit"
7
v-model="todo.title"
8
@blur="todo.edit = false; $emit('update')"
9
@keyup.enter="todo.edit=false; $emit('update')"
10
v-focus
11
>
12
<div v-else>
13
<label @click="todo.edit = true;"> {{todo.title}} </label>
14
</div>
15
</li>
16
</ul>
17
</div>
18
You can find more info here https://v2.vuejs.org/v2/guide/custom-directive.html