vue.js 实现grid
Vue.js 实现 Grid 布局
Vue.js 可以通过多种方式实现 Grid 布局,以下是几种常见的方法:
使用 CSS Grid 布局
CSS Grid 是一种强大的布局系统,可以直接在 Vue 组件中使用。以下是一个简单的示例:
<template>
<div class="grid-container">
<div v-for="item in items" :key="item.id" class="grid-item">
{{ 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' },
{ id: 4, content: 'Item 4' },
]
}
}
}
</script>
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 16px;
}
.grid-item {
background-color: #f0f0f0;
padding: 16px;
border-radius: 4px;
}
</style>
使用第三方库(如 Vuetify)
Vuetify 是一个流行的 Vue UI 框架,提供了现成的 Grid 组件:
<template>
<v-container>
<v-row>
<v-col v-for="item in items" :key="item.id" cols="12" sm="6" md="4" lg="3">
<v-card>
<v-card-text>
{{ item.content }}
</v-card-text>
</v-card>
</v-col>
</v-row>
</v-container>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, content: 'Item 1' },
{ id: 2, content: 'Item 2' },
{ id: 3, content: 'Item 3' },
{ id: 4, content: 'Item 4' },
]
}
}
}
</script>
使用 Bootstrap Vue
Bootstrap Vue 也提供了 Grid 系统:
<template>
<b-container>
<b-row>
<b-col v-for="item in items" :key="item.id" sm="6" md="4" lg="3">
<b-card>
{{ item.content }}
</b-card>
</b-col>
</b-row>
</b-container>
</template>
自定义 Grid 组件
可以创建一个可复用的 Grid 组件:
<!-- Grid.vue -->
<template>
<div class="grid" :style="gridStyle">
<slot></slot>
</div>
</template>
<script>
export default {
props: {
columns: {
type: Number,
default: 3
},
gap: {
type: String,
default: '16px'
}
},
computed: {
gridStyle() {
return {
display: 'grid',
gridTemplateColumns: `repeat(${this.columns}, 1fr)`,
gap: this.gap
}
}
}
}
</script>
使用示例:
<template>
<Grid :columns="4" gap="24px">
<div v-for="item in items" :key="item.id">
{{ item.content }}
</div>
</Grid>
</template>
响应式 Grid
可以结合 Vue 的响应式特性实现动态 Grid:
<template>
<div class="grid" :style="gridStyle">
<div v-for="item in items" :key="item.id" class="item">
{{ item.content }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [...],
columns: 3
}
},
computed: {
gridStyle() {
return {
display: 'grid',
gridTemplateColumns: `repeat(${this.columns}, 1fr)`,
gap: '16px'
}
}
},
mounted() {
window.addEventListener('resize', this.handleResize)
this.handleResize()
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize)
},
methods: {
handleResize() {
if (window.innerWidth < 600) {
this.columns = 1
} else if (window.innerWidth < 900) {
this.columns = 2
} else {
this.columns = 3
}
}
}
}
</script>
这些方法提供了不同复杂度的 Grid 实现方案,可以根据项目需求选择合适的方案。CSS Grid 提供了最大的灵活性,而 UI 框架如 Vuetify 或 Bootstrap Vue 则提供了开箱即用的解决方案。







