<template>
  <div ref="parentDiv" class="parent">
    <div v-for="(item, index) in items" :key="index" v-show="visibleItems.includes(index)" class="child">
      {{ item.content }}
    </div>
  </div>
</template>


<script setup lang="ts">
import { ref, onMounted, watchEffect } from 'vue';

// 假设这是你的数据
const items = ref([
  { content: 'Item1' },
  { content: 'Item2' },
  { content: 'Item3' },
  { content: 'Item4' },
  { content: 'Item5' },
  { content: 'Item6' },
  { content: 'Item7' },
  { content: 'Item9' },
  { content: 'Item10' },
  { content: 'Item11' },
  { content: 'Item12' },
  { content: 'Item13' },
  // 添加更多项...
]);

// 用于存储可见项的索引
const visibleItems = ref<number[]>([]);

// 父div和子div的引用
const parentDiv = ref<HTMLElement | null>(null);

// 计算并更新可见项
const updateVisibleItems = () => {
  if (!parentDiv.value) return;
  
  let totalWidth = 0;
  const children:any = parentDiv.value.children;
  visibleItems.value = [];

  for (let i = 0; i < children.length; i++) {
    const childWidth = children[i].offsetWidth + parseInt(getComputedStyle(children[i]).marginRight, 16);
    
    // console.log(parentDiv.value.offsetWidth, '<=== parentDiv.value.offsetWidth')
    // console.log(totalWidth, childWidth, '<=== ')

    if (totalWidth + childWidth > parentDiv.value.offsetWidth) break;
    
    totalWidth += childWidth;
    visibleItems.value.push(i);
    // console.log('执行语法', visibleItems.value)
  }
};

// 组件挂载后和窗口大小改变时更新可见项
onMounted(() => {
  updateVisibleItems();
  window.addEventListener('resize', updateVisibleItems);
});

watchEffect(() => {
  updateVisibleItems();
});
</script>


<style scoped>
.parent {
  display: flex;
  overflow: hidden;
  width: 100%; /* 可以根据实际情况调整 */
}

.child {
  margin-right: 10px; /* 根据实际情况调整 */
  padding: 5px; /* 根据实际情况调整 */
  text-wrap: nowrap;
}
</style>

