javascript(vue) 中的拼接在动态添加 class 后无法按预期工作
splice in javascript(vue) not working as expected after adding class dynamically
我正在尝试使用数组拼接方法从数组中删除一个元素。
我也在使用 animate.css 并在删除元素之前动态添加 class 'fadeOutDown' 。然后我使用超时函数等待动画完成并使用索引从数组中删除元素。
当我单击删除按钮时,元素的索引会执行动画,但另外下一个索引也会从 DOM 中删除,但不会从数组中删除。
在 html 和用于删除元素的 js 函数下方:
<ul class="list-group todos mx-auto text-light">
<li v-for="(todo , i) in filterTodo" :key="i"
class="list-group-item d-flex justify-content-between align-items-center
animated slideInUp slow">
<span>{{ todo }}</span>
<i @click="removeTodo(i , $event)" class="fa fa-trash-o delete">x</i>
</li>
</ul>
removeTodo(id, e) {
e.target.parentElement.classList.remove("slideInUp");
e.target.parentElement.classList.add("fadeOutDown");
setTimeout(() => {
this.todos.splice(id, 1);
}, 1000);
}
问题是将 index
用作 key
。
<li
v-for="(todo , i) in filterTodo"
:key="i" // this will make that bug.
...
您不应将 index
用作 key
,尤其是当数组可以 更新 .
时
与其使用 index
作为键,不如在每个 filterTodo 项中使用唯一的 string 或 index 更好。
如果 todo 是唯一的,您可以直接将其用作键,如下所示:
<li
v-for="(todo , i) in filterTodo"
:key="todo"
...
我正在尝试使用数组拼接方法从数组中删除一个元素。 我也在使用 animate.css 并在删除元素之前动态添加 class 'fadeOutDown' 。然后我使用超时函数等待动画完成并使用索引从数组中删除元素。
当我单击删除按钮时,元素的索引会执行动画,但另外下一个索引也会从 DOM 中删除,但不会从数组中删除。
在 html 和用于删除元素的 js 函数下方:
<ul class="list-group todos mx-auto text-light">
<li v-for="(todo , i) in filterTodo" :key="i"
class="list-group-item d-flex justify-content-between align-items-center
animated slideInUp slow">
<span>{{ todo }}</span>
<i @click="removeTodo(i , $event)" class="fa fa-trash-o delete">x</i>
</li>
</ul>
removeTodo(id, e) {
e.target.parentElement.classList.remove("slideInUp");
e.target.parentElement.classList.add("fadeOutDown");
setTimeout(() => {
this.todos.splice(id, 1);
}, 1000);
}
问题是将 index
用作 key
。
<li
v-for="(todo , i) in filterTodo"
:key="i" // this will make that bug.
...
您不应将 index
用作 key
,尤其是当数组可以 更新 .
与其使用 index
作为键,不如在每个 filterTodo 项中使用唯一的 string 或 index 更好。
如果 todo 是唯一的,您可以直接将其用作键,如下所示:
<li
v-for="(todo , i) in filterTodo"
:key="todo"
...