vue 实现grid
Vue 实现 Grid 布局的方法
使用 CSS Grid 布局
Vue 可以与 CSS Grid 布局结合,快速实现灵活的网格系统。在组件的 <style> 部分定义 CSS Grid 规则,通过 display: 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: [1, 2, 3, 4, 5, 6, 7, 8, 9]
}
}
}
</script>
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
.grid-item {
background: #eee;
padding: 20px;
text-align: center;
}
</style>
使用第三方库(如 Vuetify、Element UI)
Vuetify 和 Element UI 等 Vue UI 框架提供现成的 Grid 组件,内置响应式断点系统,适合快速开发。

Vuetify 示例:

<template>
<v-container>
<v-row>
<v-col v-for="n in 4" :key="n" cols="12" sm="6" md="3">
<v-card>
<v-card-text>Item {{ n }}</v-card-text>
</v-card>
</v-col>
</v-row>
</v-container>
</template>
<script>
export default {
name: 'VuetifyGrid'
}
</script>
自定义响应式 Grid 组件
通过 Vue 的计算属性和监听窗口大小变化,实现动态调整网格列数。
<template>
<div class="custom-grid" :style="{ '--columns': columns }">
<div v-for="item in items" :key="item.id" class="custom-grid-item">
{{ item.content }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [...], // 数据源
screenWidth: window.innerWidth
}
},
mounted() {
window.addEventListener('resize', this.handleResize)
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
},
computed: {
columns() {
if (this.screenWidth < 600) return 2
if (this.screenWidth < 900) return 3
return 4
}
},
methods: {
handleResize() {
this.screenWidth = window.innerWidth
}
}
}
</script>
<style>
.custom-grid {
display: grid;
grid-template-columns: repeat(var(--columns), 1fr);
gap: 16px;
}
</style>
动态网格拖拽排序
结合 vue-draggable 库实现可拖拽的网格布局,适合需要用户自定义排序的场景。
<template>
<draggable v-model="items" class="drag-grid" @end="onDragEnd">
<div v-for="item in items" :key="item.id" class="drag-item">
{{ item.name }}
</div>
</draggable>
</template>
<script>
import draggable from 'vuedraggable'
export default {
components: { draggable },
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
]
}
},
methods: {
onDragEnd() {
// 保存新顺序到后端
}
}
}
</script>
<style>
.drag-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
.drag-item {
background: #f5f5f5;
padding: 20px;
cursor: move;
}
</style>
选择方法时应考虑项目需求:纯 CSS Grid 适合轻量级定制,UI 框架适合快速开发,自定义组件适合特殊交互需求。






