Todo.vue 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <template>
  2. <li class="todo" :class="{ completed: todo.done, editing: editing }">
  3. <div class="view">
  4. <input class="toggle"
  5. type="checkbox"
  6. :checked="todo.done"
  7. @change="toggleTodo({ todo: todo })">
  8. <label v-text="todo.text" @dblclick="editing = true"></label>
  9. <button class="destroy" @click="deleteTodo({ todo: todo })"></button>
  10. </div>
  11. <input class="edit"
  12. v-show="editing"
  13. v-focus="editing"
  14. :value="todo.text"
  15. @keyup.enter="doneEdit"
  16. @keyup.esc="cancelEdit"
  17. @blur="doneEdit">
  18. </li>
  19. </template>
  20. <script>
  21. import { mapMutations } from 'vuex'
  22. export default {
  23. name: 'Todo',
  24. props: ['todo'],
  25. data () {
  26. return {
  27. editing: false
  28. }
  29. },
  30. directives: {
  31. focus (el, { value }, { context }) {
  32. if (value) {
  33. context.$nextTick(() => {
  34. el.focus()
  35. })
  36. }
  37. }
  38. },
  39. methods: {
  40. ...mapMutations([
  41. 'editTodo',
  42. 'toggleTodo',
  43. 'deleteTodo'
  44. ]),
  45. doneEdit (e) {
  46. const value = e.target.value.trim()
  47. const { todo } = this
  48. if (!value) {
  49. this.deleteTodo({
  50. todo
  51. })
  52. } else if (this.editing) {
  53. this.editTodo({
  54. todo,
  55. value
  56. })
  57. this.editing = false
  58. }
  59. },
  60. cancelEdit (e) {
  61. e.target.value = this.todo.text
  62. this.editing = false
  63. }
  64. }
  65. }
  66. </script>