javascript - 数据驱动的 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>
每个单元格上的虚线边框是由nugget-grid-item
CSS 类引起的,但 CSS 在这里不相关,所以让我们忽略它。
Vue 中没有类似this.children
React 的东西吗?
解决方案
你需要的是插槽。请参阅此处的文档。正如您将看到的,插槽允许父组件将 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>
推荐阅读
- python - NameError:名称 xxxxxx 未在烧瓶中定义
- c# - 如何获得前导 0x0 的十六进制 IntPtr?
- r - 如何在 R 中制作多面散点图?
- python - 带有 Pycharm 的项目解释器(带有 Anaconda 插件)。我该如何解决这个错误,告诉我 pycharm“无法创建解释器”?
- java - 如何找到内部地图值的平均值
- google-apps-script - Google App Script可以在本地保存Google Doc吗?
- sql - SELECT WHERE LIKE 返回不完整的结果,原因不是变音符号
- cassandra - Cassandra 对非分区键的行级访问控制
- kubernetes - kubectl - 检索当前/“新”副本集以进行 json 格式的部署
- amazon-web-services - 授予对第三方 lambda 函数的访问权限以写入我的 Redshift