Skip to content
Advertisement

Click-and-edit text input with Vue

I’m looking for a click-and-edit Vue component.

I’ve found a fiddle and made some edits. It works like this:

enter image description here

The fiddle is here.

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:

<div id="app">
Click the values to edit!
  <ul class="todo-list">
    <li v-for = "todo in todos">
      <input v-if = "todo.edit" v-model = "todo.title"
      @blur= "todo.edit = false; $emit('update')"
      @keyup.enter = "todo.edit=false; $emit('update')">
            <div v-else>
        <label @click = "todo.edit = true;"> {{todo.title}} </label>
      </div>
    </li>
  </ul>


</div>

JS:

new Vue({
  el: '#app',
  data: {
    todos: [{'title':'one value','edit':false},
                  {'title':'one value','edit':false},
                    {'title':'otro titulo','edit':false}],
    editedTodo: null,
    message: 'Hello Vue.js!'
  },
  methods: {
    editTodo: function(todo) {
      this.editedTodo = todo;
    },
  }

})

Advertisement

Answer

You can use a directive, for example

JS

new Vue({
  el: '#app',
  data: {
    todos: [
      { title: 'one value', edit: false },
      { title: 'one value', edit: false },
      { title: 'otro titulo', edit: false }
    ],
    editedTodo: null,
    message: 'Hello Vue.js!'
  },
  methods: {
    editTodo: function (todo) {
      this.editedTodo = todo
    }
  },
  directives: {
    focus: {
      inserted (el) {
        el.focus()
      }
    }
  }
})

HTML

<div id="app">
    Click the values to edit!
    <ul class="todo-list">
        <li v-for="todo in todos">
            <input
                v-if="todo.edit"
                v-model="todo.title"
                @blur="todo.edit = false; $emit('update')"
                @keyup.enter="todo.edit=false; $emit('update')"
                v-focus
            >
            <div v-else>
                <label @click="todo.edit = true;"> {{todo.title}} </label>
            </div>
        </li>
    </ul>
</div>

You can find more info here https://v2.vuejs.org/v2/guide/custom-directive.html

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement