Vue中无ID纯字符串数组如何匹配对应字符串并删除匹配项
实现方案
你直接基于字符串匹配查找索引后调用splice删除即可,Vue本身支持监听splice这类数组变异方法的操作,修改后会自动触发视图更新:
new Vue({ el: "#app", props: { }, data: { tierArray:['one', 'two', 'three'], }, methods: { removeTierSelection(value){ // 查找目标字符串在数组中的索引,无匹配时返回-1 const matchIndex = this.tierArray.indexOf(value.name) // 匹配到对应元素再执行删除 if (matchIndex !== -1) { // 第一个参数为删除起始索引,第二个参数为删除元素数量 this.tierArray.splice(matchIndex, 1) } }, } })
批量删除同值元素的补充方案
如果数组中可能存在多个相同的字符串,需要全部删除的话,可以直接用filter生成新数组覆盖原数组,同样能触发响应式更新:
removeTierSelection(value){ this.tierArray = this.tierArray.filter(item => item !== value.name) }
说明
- 两种方案都是基于严格相等匹配(即
===规则),和你的需求完全契合 - 不需要额外给数组元素加ID,纯字符串对比即可正常运行
内容的提问来源于stack exchange,提问作者Geoff_S
相关产品推荐
相关产品推荐

