<view class="selectFood" v-for="(item,index) in selectFood" :key="item" v-if="this.selectFood.length>0"> <image :src="item.imgUrl" mode=""></image> <p>{{item.data}}</p> <view class="select-icon"> <image src="../../static/squareImg/delete.png" mode=""></image> </view> </view> 现在有个数组selectFood,数组中有很多对象,现在我如果要随机点击select-icon的图片,对应的那条数组中的数据就被删除,如何实现
时间: 2023-08-06 11:04:48 浏览: 111
要实现点击 `select-icon` 图片后删除对应的数组中的数据,你可以在点击事件中获取当前点击的索引,然后使用该索引从 `selectFood` 数组中删除对应的元素。以下是一个示例代码:
```javascript
<template>
<div>
<div v-for="(item, index) in selectFood" :key="index" class="selectFood">
<img :src="item.imgUrl" mode="">
<p>{{ item.data }}</p>
<div class="select-icon">
<img src="../../static/squareImg/delete.png" mode="" @click="deleteItem(index)">
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
selectFood: [
{ imgUrl: '...', data: '...' },
{ imgUrl: '...', data: '...' },
// more items
]
};
},
methods: {
deleteItem(index) {
this.selectFood.splice(index, 1);
}
}
};
</script>
<style>
/* CSS styles for selectFood and select-icon */
</style>
```
在上述代码中,我们使用 `v-for` 指令遍历 `selectFood` 数组,并为每个元素渲染一个 `selectFood` div。在 `select-icon` 图片上添加了点击事件 `@click`,并传递了当前项的索引 `index` 给 `deleteItem()` 方法。在 `deleteItem()` 方法中,我们使用 `splice()` 方法从 `selectFood` 数组中删除了对应索引位置的元素。这样就能实现点击图片后删除对应的数组数据。
阅读全文