如何将更改存储在javascript对象中,以便以后用Vue恢复它们?

问题描述 投票:0回答:1

我有一个todo应用程序。功能很简单:你可以添加一个带有待办事项列表的笔记。你以后可以在笔记编辑页面编辑它(添加更多的待办事项)。但我还需要一个功能来存储 "笔记 "对象的变化在数组中,以便以后能够恢复它们。

模板。

<form class="note">
      <h4>Edit Note <span v-if="note.title">"{{ note.title }}"</span></h4>
      <input
        type="text"
        placeholder="Enter note title"
        v-model.lazy="note.title"
      >
      <div class="createTodoWrapper">
        <input
          type="text"
          placeholder="Add todo"
          v-model="todoTitle"
        >
        <button
          @click.prevent="addTodo"
          class="addTodoBtn"
        >+</button>
      </div>
      <ul
        class="todosList"
        v-if="note.todos"
      >
        <h4>Todos:</h4>
        <li
          v-for="todo in note.todos"
          :key="todo.id"
        >
          <p>{{ todo.title }}</p>
          <input
            type="checkbox"
            v-model="todo.completed"
          >
        </li>
      </ul>
      <p v-else>No todos yet</p>
      <div class="buttonsWrapper">
        <button @click.prevent="saveChanges">Save</button>
        <button @click.prevent="revertChanges">Revert</button>
        <button @click.prevent="redoChanges">Redo</button>
        <button
          @click.prevent="showModalDelete = true"
          class="deleteBtn"
        >Delete</button>
        <button @click.prevent="showCancelEditModal = !showCancelEditModal">Cancel</button>
      </div>
    </form>

note就是这样的。

{"id":"1723d1fffa7","title":"Test","todos":[{"title":"first","id":"1723d83bbe7","completed":false},{"title":"second","id":"1723d83cca7","completed":false}]}

这是一些逻辑

// I detect changes and put newVal in an array
watch: {
    note: {
      handler: function(val) {
        if(val) {
          let item = this.cloneNote(val)
          this.noteHistory.push(item)
          console.log('newVal')
        }
      },
      deep: true
    }
  },

revertChanges() {
      if (this.counter <= this.noteHistory.length) {
        this.counter ++
        this.note = this.noteHistory[this.noteHistory.length - this.counter]
      }
    },

但当我恢复更改时,观察者又会触发,我的更改历史数组就会增加!

我怎样才能避免这种情况呢?

javascript arrays sorting vue.js watch
1个回答
1
投票

我想到的第一个想法是有一个 "笔记 "对象的变化。isUndoing 属性,以短路历史更新。

data() {
  return {
    isUndoing: false
  }
},

methods: {
  revertChanges() {
    this.isUndoing = true
    // existing code
    this.isUndoing = false
  }
},

watch: {
  note: {
    handler: function(val) {
      if(val && !this.isUndoing) {
        // existing code
      }
    },
    deep: true
  }
}

如果你想为重做案例命名得更通用一些,它可以是 isManipulatingHistory.

© www.soinside.com 2019 - 2024. All rights reserved.