首页 > 解决方案 > 按字母表排列在不同列中的垂直顺序

问题描述

A | B | D | F
A | C | E | G
B | C |

我有一组数据:

3列示例

A | C | E
A | C | F
B | D | G
B |

CSS 中的column-count是目前最好的,但在响应式上工作错误

我在考虑 Vue.js,它取决于屏幕大小(可以添加/删除列)并在列之间移动数组数据

我为 HTML 使用引导程序

这是我所做的代码,但这还不足以满足需要https://codepen.io/alexander-chumak/pen/JvyLPJ的工作

标签: javascripthtmlcssvue.js

解决方案


由于您使用的是 Vue,因此我将按列对项目使用计算值。这样,当 items 或 columnCount 更改时,您无需担心自己重新运行任何内容。

您可以执行以下操作:

data () {
  return {
    columnCount: 2,
    items: [],
  }
},

created () {
  // You should debounce this callback.
  window.addEvenetListener('resize', this.updateColumnCount)
  this.updateColumnCount()
},

destroyed () {
  window.removeEventListener('resize', this.updateColumnCount)
},

methods: {
  updateColumnCount () {
    // updat the columnCount here like: this.columnCount = 2
  },
},

computed: {
  itemsByColumn () {
    return this.items.reduce((columns, item, index) => {
      const columnNumber = index % this.columnCount

      if (!columns[columnNumber]) {
        columns[columnNumber] = []
      }

      columns[columnNumber].push(item)

      return columns
    })
  },
},

然后,在您的模板中,您可以执行以下操作:

<div class="flex">
  <div class="column" v-for="(column, index) in itemsByColumn" :key="index">
    <div class="item" v-for="item in column" :key="item.id">
      {{ item.name }}
    </div>
  </div>
</div>

这段代码没有经过测试,但它应该能让你大部分时间到达那里。


推荐阅读