vue 实现grid
Vue 实现 Grid 布局的方法
使用 CSS Grid 布局
Vue 可以与 CSS Grid 布局结合,通过模板和样式实现灵活的网格布局。CSS Grid 提供强大的二维布局能力,适合复杂网格需求。
<template>
<div class="grid-container">
<div v-for="(item, index) in items" :key="index" class="grid-item">
{{ item }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6']
}
}
}
</script>
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 16px;
}
.grid-item {
background: #f0f0f0;
padding: 16px;
text-align: center;
}
</style>
使用第三方组件库
对于快速开发,可以使用现成的 Vue 组件库如 Element UI、Vuetify 或 Ant Design Vue,它们提供内置的 Grid 组件。
以 Element UI 为例:

<template>
<el-row :gutter="20">
<el-col :span="6" v-for="(item, index) in items" :key="index">
<div class="grid-item">{{ item }}</div>
</el-col>
</el-row>
</template>
<script>
export default {
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3', 'Item 4']
}
}
}
</script>
<style>
.grid-item {
background: #f0f0f0;
padding: 16px;
text-align: center;
}
</style>
自定义 Grid 组件
如果需要高度定制化的 Grid,可以创建自定义组件。通过 props 接收配置(如列数、间距),动态生成布局。
<template>
<div class="custom-grid" :style="gridStyle">
<slot></slot>
</div>
</template>
<script>
export default {
props: {
columns: {
type: Number,
default: 3
},
gap: {
type: String,
default: '16px'
}
},
computed: {
gridStyle() {
return {
'display': 'grid',
'grid-template-columns': `repeat(${this.columns}, 1fr)`,
'gap': this.gap
}
}
}
}
</script>
使用示例:

<custom-grid :columns="4" gap="24px">
<div v-for="(item, index) in items" :key="index">
{{ item }}
</div>
</custom-grid>
响应式 Grid 设计
通过媒体查询或 CSS 变量实现响应式 Grid,适应不同屏幕尺寸。
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 16px;
}
或在 Vue 中动态计算:
computed: {
columns() {
return window.innerWidth < 768 ? 2 : 4
}
}






