vue实现gridlayout
Vue 实现 GridLayout
在 Vue 中实现 GridLayout 可以通过多种方式完成,以下是几种常见的方法:
使用 CSS Grid
CSS Grid 是一种强大的布局系统,可以直接在 Vue 组件的样式中使用。
<template>
<div class="grid-container">
<div class="grid-item" v-for="item in items" :key="item.id">
{{ item.content }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, content: 'Item 1' },
{ id: 2, content: 'Item 2' },
{ id: 3, content: 'Item 3' }
]
}
}
}
</script>
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
.grid-item {
background: #f0f0f0;
padding: 20px;
text-align: center;
}
</style>
使用第三方库 vue-grid-layout
vue-grid-layout 是一个专门为 Vue 设计的拖拽网格布局库,适合需要动态调整布局的场景。
安装依赖:

npm install vue-grid-layout --save
示例代码:
<template>
<grid-layout
:layout="layout"
:col-num="12"
:row-height="30"
:is-draggable="true"
:is-resizable="true"
@layout-updated="layoutUpdatedEvent"
>
<grid-item
v-for="item in layout"
:key="item.i"
:x="item.x"
:y="item.y"
:w="item.w"
:h="item.h"
:i="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' },
{ x: 4, y: 0, w: 2, h: 5, i: '2' }
]
}
},
methods: {
layoutUpdatedEvent(newLayout) {
console.log('Updated layout: ', newLayout)
}
}
}
</script>
使用 Bootstrap Vue 的网格系统
Bootstrap Vue 提供了响应式的网格系统,适合快速搭建布局。
安装依赖:

npm install bootstrap-vue bootstrap
示例代码:
<template>
<b-container class="bv-example-row">
<b-row>
<b-col v-for="item in items" :key="item.id" cols="12" md="4">
{{ item.content }}
</b-col>
</b-row>
</b-container>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, content: 'Item 1' },
{ id: 2, content: 'Item 2' },
{ id: 3, content: 'Item 3' }
]
}
}
}
</script>
<style>
.bv-example-row {
padding: 20px;
}
</style>
使用 Vue 的动态组件
如果需要更灵活的布局,可以结合动态组件和 CSS Grid 或 Flexbox。
<template>
<div class="dynamic-grid">
<component
v-for="(component, index) in components"
:key="index"
:is="component.type"
v-bind="component.props"
/>
</div>
</template>
<script>
export default {
data() {
return {
components: [
{ type: 'CustomComponent1', props: { text: 'Component 1' } },
{ type: 'CustomComponent2', props: { text: 'Component 2' } }
]
}
},
components: {
CustomComponent1: {
template: '<div class="grid-item">{{ text }}</div>',
props: ['text']
},
CustomComponent2: {
template: '<div class="grid-item">{{ text }}</div>',
props: ['text']
}
}
}
</script>
<style>
.dynamic-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 10px;
}
.grid-item {
background: #f0f0f0;
padding: 20px;
text-align: center;
}
</style>
总结
以上方法可以根据具体需求选择:
- 简单布局使用 CSS Grid
- 动态拖拽布局使用 vue-grid-layout
- 快速响应式布局使用 Bootstrap Vue
- 灵活组件布局使用动态组件






