首页 > 解决方案 > 数据驱动的 CSS 网格 Vue 组件

问题描述

我想创建一个 Grid 组件,它接受来自用户的列数,接受数据并将其所有子项呈现到连续的单元格中。

像这样的东西。

<Grid :cells="12" :columns="6">
    <div>Child1 Cell1</div>
    <div>Child2 Cell2</div>
    <div>Child3 Cell3</div>
    <div>Child4 Cell4</div>
    <div>Child5 Cell5</div>
    <div>Child6 Cell6</div>
</Grid>

在模板中的 Grid.vue 组件中,这是我期望做的。

<div class="nugget-grid-item" v-for="cell of cells" :key="cell">
    {cell}
</div>

这将在 UI 上呈现类似的内容。 网格

每个单元格上的虚线边框是由nugget-grid-itemCSS 类引起的,但 CSS 在这里不相关,所以让我们忽略它。

我无法弄清楚的是如何让这个 Grid 组件显示以下内容。 在此处输入图像描述

Vue 中没有类似this.childrenReact 的东西吗?

标签: javascriptreactjsvue.jsvuejs2vue-component

解决方案


你需要的是插槽。请参阅此处的文档。正如您将看到的,插槽允许父组件将 DOM 元素传递给子组件。对它们的基本了解可以是这样的:

//ChildComponent.vue
<template>
  <div>
    <p>I'm the child component!</p>
    <!-- Content from the parent gets rendered here. -->
    <slot></slot>
  </div>
</template>

然后你将内容注入槽标签,如下所示:

//ParentComponent.vue
<template>
  <div>
    <child-component>
      <p>I'm injected content from the parent!</p>
      <p>I can still bind to data in the parent's scope, like this! {{myVariable}}</p>
    </child-component>
  </div>
</template>

老虎机可能会变得非常复杂并且可以做很多事情,因此非常值得研究。

除了您的以下评论,您可以在网格中放置一个 v-for 。这会输出您似乎想要的东西。正如你所说,我已经输入了一个输入来接受用户的列数,然后它会呈现该数量的单元格。您当然可以使用多个插槽、命名插槽和作用域插槽,但我将由您自己决定如何扩展它。

//Grid.vue
<template>
    <div class="cell">
        <slot></slot>
    </div>
</template>

<script>
export default {

}
</script>
 <style scoped>
    .cell {
        height: 40px;
        width: 60px;
        border: 1px solid gray;
    }
 </style>

和家长:

<template>
    <div class="content">

        <label>Enter number of columns</label>
        <input v-model.number="col" type="number">
        <Grid v-for="(n, i) in col" :key="i" >
            <div>Child{{n}} Cell{{n}}</div>
        </Grid>
    </div>
</template>

<script>

import Grid from '@/components/admin/Grid'

export default {
    layout: 'admin',
    components: {
        Grid
    },
    data: () => ({

        col: 4
    }),
}
</script>

推荐阅读