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>
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
padding: 10px;
}
.grid-item {
background-color: #f0f0f0;
padding: 20px;
text-align: center;
}
</style>
使用第三方库(如 vue-grid-layout)
如果需要拖拽、动态调整大小等高级功能,可以使用 vue-grid-layout 库。
npm install vue-grid-layout --save
<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.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: "0" },
{ x: 2, y: 0, w: 2, h: 4, i: "1" },
],
};
},
};
</script>
响应式 Grid 布局
结合 CSS Grid 和 Vue 的响应式特性,可以实现适应不同屏幕尺寸的布局。
<template>
<div class="responsive-grid">
<div v-for="(item, index) in items" :key="index" class="responsive-item">
{{ item }}
</div>
</div>
</template>
<style>
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 15px;
}
@media (max-width: 600px) {
.responsive-grid {
grid-template-columns: 1fr;
}
}
</style>
动态生成 Grid 布局
通过 Vue 的数据绑定,可以动态生成和更新 Grid 布局。
<template>
<div class="dynamic-grid" :style="gridStyle">
<div v-for="(item, index) in dynamicItems" :key="index" class="dynamic-item">
{{ item.text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
dynamicItems: [
{ text: "Item 1" },
{ text: "Item 2" },
{ text: "Item 3" },
],
columns: 3,
};
},
computed: {
gridStyle() {
return {
display: "grid",
"grid-template-columns": `repeat(${this.columns}, 1fr)`,
gap: "10px",
};
},
},
};
</script>
这些方法覆盖了从基础 CSS Grid 实现到高级动态布局的需求,可以根据具体场景选择适合的方案。







