index.vue 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <template>
  2. <div ref="parentDiv" class="parent">
  3. <div v-for="(item, index) in items" :key="index" v-show="visibleItems.includes(index)" class="child">
  4. {{ item.content }}
  5. </div>
  6. </div>
  7. </template>
  8. <script setup lang="ts">
  9. import { ref, onMounted, watchEffect } from 'vue';
  10. // 假设这是你的数据
  11. const items = ref([
  12. { content: 'Item1' },
  13. { content: 'Item2' },
  14. { content: 'Item3' },
  15. { content: 'Item4' },
  16. { content: 'Item5' },
  17. { content: 'Item6' },
  18. { content: 'Item7' },
  19. { content: 'Item9' },
  20. { content: 'Item10' },
  21. { content: 'Item11' },
  22. { content: 'Item12' },
  23. { content: 'Item13' },
  24. // 添加更多项...
  25. ]);
  26. // 用于存储可见项的索引
  27. const visibleItems = ref<number[]>([]);
  28. // 父div和子div的引用
  29. const parentDiv = ref<HTMLElement | null>(null);
  30. // 计算并更新可见项
  31. const updateVisibleItems = () => {
  32. if (!parentDiv.value) return;
  33. let totalWidth = 0;
  34. const children:any = parentDiv.value.children;
  35. visibleItems.value = [];
  36. for (let i = 0; i < children.length; i++) {
  37. const childWidth = children[i].offsetWidth + parseInt(getComputedStyle(children[i]).marginRight, 16);
  38. // console.log(parentDiv.value.offsetWidth, '<=== parentDiv.value.offsetWidth')
  39. // console.log(totalWidth, childWidth, '<=== ')
  40. if (totalWidth + childWidth > parentDiv.value.offsetWidth) break;
  41. totalWidth += childWidth;
  42. visibleItems.value.push(i);
  43. // console.log('执行语法', visibleItems.value)
  44. }
  45. };
  46. // 组件挂载后和窗口大小改变时更新可见项
  47. onMounted(() => {
  48. updateVisibleItems();
  49. window.addEventListener('resize', updateVisibleItems);
  50. });
  51. watchEffect(() => {
  52. updateVisibleItems();
  53. });
  54. </script>
  55. <style scoped>
  56. .parent {
  57. display: flex;
  58. overflow: hidden;
  59. width: 100%; /* 可以根据实际情况调整 */
  60. }
  61. .child {
  62. margin-right: 10px; /* 根据实际情况调整 */
  63. padding: 5px; /* 根据实际情况调整 */
  64. text-wrap: nowrap;
  65. }
  66. </style>