vue grid实现
Vue Grid 实现方法
在 Vue 中实现网格布局可以通过多种方式完成,包括使用原生 CSS Grid、第三方组件库或自定义组件。以下是几种常见方法:
使用原生 CSS Grid
通过 Vue 的模板结合 CSS Grid 实现灵活的网格布局:
<template>
<div class="grid-container">
<div v-for="(item, index) in items" :key="index" class="grid-item">
{{ item }}
</div>
</div>
</template>
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 16px;
}
.grid-item {
background: #f0f0f0;
padding: 20px;
text-align: center;
}
</style>
使用第三方组件库
Vuetify、Element Plus 等流行 UI 库提供了现成的网格组件:

Vuetify 示例:
<template>
<v-container>
<v-row>
<v-col v-for="(item, index) in items" :key="index" cols="12" sm="6" md="4">
{{ item }}
</v-col>
</v-row>
</v-container>
</template>
Element Plus 示例:

<template>
<el-row :gutter="20">
<el-col v-for="(item, index) in items" :key="index" :span="8">
{{ item }}
</el-col>
</el-row>
</template>
响应式网格实现
结合 Vue 的计算属性实现动态网格列数:
<template>
<div
class="dynamic-grid"
:style="{ 'grid-template-columns': `repeat(${columnCount}, 1fr)` }"
>
<div v-for="(item, index) in items" :key="index">
{{ item }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [/* 数据项 */],
screenWidth: window.innerWidth
}
},
computed: {
columnCount() {
if (this.screenWidth < 600) return 2
if (this.screenWidth < 900) return 3
return 4
}
},
mounted() {
window.addEventListener('resize', () => {
this.screenWidth = window.innerWidth
})
}
}
</script>
拖拽排序网格
使用 vue-draggable 实现可拖拽网格:
<template>
<draggable
v-model="items"
class="drag-grid"
item-key="id"
@end="onDragEnd"
>
<template #item="{element}">
<div class="drag-item">
{{ element.name }}
</div>
</template>
</draggable>
</template>
<script>
import draggable from 'vuedraggable'
export default {
components: { draggable },
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
// 其他项...
]
}
}
}
</script>
性能优化建议
对于大型网格列表,建议使用虚拟滚动技术:
- 使用
vue-virtual-scroller等库 - 仅渲染可视区域内的网格项
- 减少 DOM 节点数量提升性能
<template>
<RecycleScroller
class="virtual-grid"
:items="largeList"
:item-size="100"
key-field="id"
v-slot="{ item }"
>
<div class="virtual-item">
{{ item.name }}
</div>
</RecycleScroller>
</template>






