【发布时间】:2020-05-22 17:57:16
【问题描述】:
我有一个待办事项应用程序。功能很简单:您可以添加带有待办事项列表的注释。您可以稍后在注释编辑页面上对其进行编辑(添加更多待办事项)。但我还需要一个功能来将“注释”对象更改存储在数组中,以便以后能够恢复它们。
模板:
<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]
}
},
但是当我恢复更改时,观察者再次触发并且我的更改历史数组增长!
我怎样才能避免这种情况?
【问题讨论】:
-
您可以动态添加和删除手表:codingexplained.com/coding/front-end/vue-js/…,否则您可以使用带有
on:change事件的方法而不是手表
标签: javascript arrays sorting vue.js watch