You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js不使用CSS如何将列表拆分为每行3项且保留原有编辑功能

解决方案

核心思路是通过JS将原一维数组按每3个元素为一组拆分,嵌套渲染每组为独立行(块级元素默认独占一行),不需要新增任何CSS代码,原有编辑、选中逻辑完全不需要改动。

第一步:新增分组计算属性

在item-list组件的computed配置中添加分组逻辑:

computed: {
  activeItemValue() {
    return this.items[this.activeIndex]?.title ?? '';
  },
  // 新增分组计算属性
  groupedItems() {
    const groups = []
    for (let i = 0; i < this.items.length; i += 3) {
      groups.push(this.items.slice(i, i + 3))
    }
    return groups
  }
}

第二步:修改列表渲染模板

调整item-list-template中的列表循环逻辑,改为嵌套循环,内层元素计算全局索引匹配原有逻辑:

<script type="text/x-template" id="item-list-template">
  <div>
    <input type="text" placeholder="Edit selected items" :value="activeItemValue" @input="setActiveItemValue" />
    <div class="items-col">
      <!-- 先遍历所有分组,每个分组对应一行 -->
      <ul class="items-list" v-for="(group, groupIndex) in groupedItems" :key="groupIndex">
        <!-- 遍历分组内的元素,计算全局索引 -->
        <item 
          v-for="(item, itemIndex) in group" 
          :key="groupIndex * 3 + itemIndex" 
          :title="item.title" 
          :isActive="activeIndex === groupIndex * 3 + itemIndex" 
          @click.native="onItemClick(groupIndex * 3 + itemIndex)" 
        />
      </ul>
    </div>
  </div>
</script>

效果说明

  • 原有flex布局会让每个ul内的3个元素排列在同一行
  • 每个ul本身是块级元素,自动独占一行,自然实现每行3个的效果
  • 全局索引计算和原数组完全对应,原有选中、编辑功能没有任何改动即可正常运行

内容的提问来源于stack exchange,提问作者Ioann Sulyma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 08:15:00