VUE v-for循环数组arr,div中显示对象中的某一值item.name,div横向排列,超出设定的长度时,div则自动换行,点击某一item.name时如何确定点击的元素是第几行的
时间: 2024-02-25 08:52:28 浏览: 25
要实现这个功能,你可以使用 Vue 的计算属性来计算每个 item 在数组中的索引以及所在的行数。具体操作步骤如下:
1. 在模板中使用 v-for 循环数组 arr,将每个 item 显示在一个 div 中,并绑定一个 click 事件。
```html
<template>
<div>
<div v-for="(item, index) in arr" :key="item.id" @click="handleClick(item)">
{{ item.name }}
</div>
</div>
</template>
```
2. 在计算属性中计算每个 item 在数组中的索引以及所在的行数。首先,需要知道每行能容纳的 item 的数量,可以根据容器的宽度和每个 item 的宽度来计算。然后,可以根据每个 item 在数组中的索引和每行能容纳的 item 的数量来计算该 item 所在的行数。
```javascript
computed: {
itemsPerRow() {
// 计算每行能容纳的 item 的数量
const containerWidth = this.$refs.container.clientWidth;
const itemWidth = this.$refs.item[0].clientWidth;
return Math.floor(containerWidth / itemWidth);
},
indexedArr() {
// 给每个 item 添加索引和行数属性
return this.arr.map((item, index) => {
const rowIndex = Math.floor(index / this.itemsPerRow);
return {
...item,
index,
rowIndex
};
});
}
}
```
3. 在 handleClick 方法中,可以通过事件对象的 target 属性获取点击的元素,然后遍历 indexedArr 数组,找到该元素对应的 item,并获取该 item 的 rowIndex 属性即可。
```javascript
methods: {
handleClick(item) {
const clickedElement = event.target;
const index = Array.from(this.$refs.item).indexOf(clickedElement);
const clickedItem = this.indexedArr[index];
console.log(clickedItem.rowIndex);
}
}
```
注意,这里需要使用 Array.from 将类数组对象转换为数组,以便使用 indexOf 方法来查找点击的元素在数组中的索引。同时,需要在每个 div 中添加一个 ref 属性,以便在计算属性中获取每个 item 的宽度。