vue实现grid
Vue 实现 Grid 布局的方法
使用 CSS Grid 布局
CSS Grid 是现代浏览器原生支持的强大布局系统,结合 Vue 可以轻松实现复杂的网格布局。
<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: 20px;
text-align: center;
}
</style>
使用第三方组件库
流行的 Vue UI 组件库如 Element UI、Vuetify 等提供了现成的 Grid 组件。
Element UI 示例:
<template>
<el-row :gutter="20">
<el-col :span="8" v-for="(item, index) in items" :key="index">
<div class="grid-content">{{ item }}</div>
</el-col>
</el-row>
</template>
<script>
import { ElRow, ElCol } from 'element-plus'
export default {
components: { ElRow, ElCol },
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6']
}
}
}
</script>
<style>
.grid-content {
background: #f0f0f0;
padding: 20px;
text-align: center;
}
</style>
使用 Vue Grid 专用库
对于高级网格需求,可以考虑专用库如 ag-Grid 或 Vue Grid Layout。
Vue Grid Layout 示例:
<template>
<grid-layout
:layout.sync="layout"
:col-num="12"
:row-height="30"
:is-draggable="true"
:is-resizable="true"
>
<grid-item v-for="item in layout" :x="item.x" :y="item.y" :w="item.w" :h="item.h" :i="item.i" :key="item.i">
{{ 'Item ' + item.i }}
</grid-item>
</grid-layout>
</template>
<script>
import { GridLayout, GridItem } from 'vue-grid-layout'
export default {
components: { GridLayout, GridItem },
data() {
return {
layout: [
{ x: 0, y: 0, w: 2, h: 2, i: '1' },
{ x: 2, y: 0, w: 2, h: 4, i: '2' },
{ x: 4, y: 0, w: 2, h: 5, i: '3' }
]
}
}
}
</script>
响应式 Grid 实现
结合 Vue 的响应式特性和 CSS 媒体查询,可以创建响应式网格。
<template>
<div class="responsive-grid">
<div v-for="(item, index) in items" :key="index" class="responsive-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>
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 16px;
}
@media (max-width: 600px) {
.responsive-grid {
grid-template-columns: 1fr;
}
}
.responsive-item {
background: #f0f0f0;
padding: 20px;
text-align: center;
}
</style>
动态 Grid 实现
利用 Vue 的计算属性或方法动态生成网格布局。
<template>
<div class="dynamic-grid" :style="gridStyle">
<div v-for="(item, index) in items" :key="index" class="dynamic-item" :style="itemStyle(index)">
{{ item }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'],
columns: 3
}
},
computed: {
gridStyle() {
return {
display: 'grid',
'grid-template-columns': `repeat(${this.columns}, 1fr)`,
gap: '16px'
}
}
},
methods: {
itemStyle(index) {
return {
background: index % 2 === 0 ? '#f0f0f0' : '#e0e0e0',
padding: '20px',
'text-align': 'center'
}
}
}
}
</script>






