1、给删除按钮绑定事件
组件:
@click="removeItemById(item.id)"
methods: {
// 通过id删除莫一项item
removeItemById(id) {
// console.log(id)
this.$store.commit('removeItem', id)
}
}
2、vuex ---实现
vuex:
mutations: {
// 根据id删除对应的任务事项
removeItem(state, id) {
// 根据id查找对应项的索引
const i = state.list.findIndex((x) => x.id === id)
// 根据索引,删除对应的元素
if (i !== -1) {
state.list.splice(i, 1)
}
}
}
findIndex() 方法返回传入一个测试条件(函数)符合条件的数组第一个元素位置。
findIndex() 方法为数组中的每个元素都调用一次函数执行:
- 当数组中的元素在测试条件时返回 true 时, findIndex() 返回符合条件的元素的索引位置,之后的值不会再调用执行函数。
- 如果没有符合条件的元素返回 -1
注意: findIndex() 对于空数组,函数是不会执行的。
注意: findIndex() 并没有改变数组的原始值。
state.list.splice(i, 1): 参数1:删除的索引,参数2:删除元素的个数