Gridbox 以符合内容大小

Gridbox to conform to content size

所以我这里有这个简单的 table:

其代码相当简单:

<template>
    <div class="table">
        <div class="table__headers">
            <h3 v-for="header in headers" :key="header.value">
                {{ header.value }}
            </h3>
        </div>
        <div class="table__body">
            <div
                v-for="(item, index) in modelData"
                :key="index"
                class="table__body--line"
            >
                <p v-for="{ property } in headers" :key="property">
                    <router-link
                        :to="{ name: 'AdminJob', params: { id: item.id } }"
                    >
                        {{ item[property] }}
                    </router-link>
                </p>
            </div>
        </div>
    </div>
    <Pagination
        v-model:current-page="meta.currentPage"
        :total="meta.total"
        v-model:per-page="meta.perPage"
    />
</template>


<style scoped lang="scss">
.table {
    border: solid 1px red;

    &__headers {
        display: grid;
        grid-gap: 10px;
        grid: 50px / auto-flow minmax(100px, 1fr);
    }

    &__body {
        display: flex;
        flex-direction: column;
        grid-gap: 10px;
        &--line {
            display: grid;
            grid-gap: 10px;
            grid: auto / auto-flow minmax(200px, 1fr);
        }
    }
}
</style>

我想要实现的是使列的宽度能够灵活地适应其中的内容。

所以在上面的基础中,由于 DetailsStatus 有更多的内容,所以它会填写更多 space .另一个警告是这个 Vue 组件显示了许多不同的 table 信息。在其他情况下,我们可能只有 2 列,而在其他情况下我们可能有 8 列,所以我试图找出一个 'global' 解决方案来解决这个问题,而不是进入每个 table 并修改宽度.

在 Grid 中有更简单的方法吗?我尝试了 Flexbox,但我无法让列像在 Grid 中那样完美对齐。

您必须在代码中使用 grid-template-columns:min-content。 这个page可以帮到你。

为了列的灵活性,您可以使用 css-variables 并将其与 Vue 的样式绑定绑定。

<template>
  <div class="table" :style="{ '--cols': counts }">
    <div v-for="header in headers" :key="header">
      <h3 class="table__headers">{{ header }}</h3>
    </div>
  </div>
</template>

<script>
export default {
  data: function () {
    return {
      headers: [
        "apple",
        "ndis officia! Perferendis ratione blanditiis repellat explicabo neque",
        "lorem ipsum dolor sit amet",
        "mango"
      ],
    };
  },
  computed: {
    counts: function () { return this.headers.length < 4 ? `${l}` : "auto-fit" },
  },
};
</script>

<style scoped>
.table {
  display: grid;
  grid-template-columns: repeat(var(--cols), minmax(100px, max-content));
  gap: 10px;
}
.table__headers { ... }
</style>