数据驱动CSS Grid Vue组件

时间:2018-11-17 04:31:44

标签: javascript reactjs vue.js vuejs2 vue-component

我想创建一个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上呈现类似这样的内容。 Grids

每个单元格上的虚线边框归因于nugget-grid-item CSS类,但是CSS与此处无关,所以我们忽略它。

我无法弄清楚的是如何获取此Grid组件以显示以下内容。 enter image description here

在Vue中是否没有类似this.children的东西?

1 个答案:

答案 0 :(得分:1)

您需要的是插槽。请参阅此处的docs。如您所见,插槽允许父组件将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>