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

How to store changes in javascript object to revert them later with Vue?

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

模板:

<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>

注释看起来像这样:

{"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]
      }
    },

但是当我还原更改时,观察器再次触发并且我的更改历史数组增长!

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

第一个想到的想法是 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