vue实现groupbox
在 Vue 中实现类似 GroupBox(分组框)的功能,可以通过自定义组件结合样式和插槽完成。以下是几种实现方法:
使用原生 HTML 和 CSS 实现
通过 <fieldset> 和 <legend> 标签实现基础分组框效果,配合 Vue 的插槽功能:

<template>
<fieldset class="group-box">
<legend>{{ title }}</legend>
<slot></slot>
</fieldset>
</template>
<script>
export default {
props: ['title']
}
</script>
<style scoped>
.group-box {
border: 1px solid #ddd;
border-radius: 4px;
padding: 10px;
margin: 10px 0;
}
legend {
padding: 0 5px;
color: #666;
}
</style>
基于第三方组件库扩展
若使用 Element UI 或 Ant Design Vue 等库,可利用现有面板组件改造:

<template>
<a-card :title="title" size="small" class="group-box">
<slot></slot>
</a-card>
</template>
<script>
import { Card } from 'ant-design-vue'
export default {
components: { 'a-card': Card },
props: ['title']
}
</script>
<style scoped>
.group-box {
margin-bottom: 16px;
}
</style>
自定义可折叠 GroupBox
实现带折叠功能的交互式分组框:
<template>
<div class="collapsible-box">
<div class="header" @click="toggle">
{{ title }}
<span class="icon">{{ isOpen ? '−' : '+' }}</span>
</div>
<div class="content" v-show="isOpen">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
props: ['title'],
data() {
return { isOpen: true }
},
methods: {
toggle() { this.isOpen = !this.isOpen }
}
}
</script>
<style scoped>
.collapsible-box {
border: 1px solid #eee;
margin: 10px 0;
}
.header {
background: #f5f5f5;
padding: 8px 12px;
cursor: pointer;
display: flex;
justify-content: space-between;
}
.content {
padding: 12px;
}
</style>
动态主题 GroupBox
通过 props 控制主题样式:
<template>
<div :class="['group-box', theme]">
<div class="title">{{ title }}</div>
<div class="content">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
props: {
title: String,
theme: {
type: String,
default: 'light',
validator: value => ['light', 'dark'].includes(value)
}
}
}
</script>
<style scoped>
.group-box {
border-radius: 4px;
margin: 10px 0;
overflow: hidden;
}
.title {
padding: 8px 12px;
font-weight: bold;
}
.content {
padding: 12px;
}
.light {
border: 1px solid #e0e0e0;
}
.light .title {
background: #f5f5f5;
color: #333;
}
.dark {
border: 1px solid #444;
}
.dark .title {
background: #222;
color: #fff;
}
</style>
以上实现方式可根据实际需求选择或组合使用。关键点在于合理利用 Vue 的组件化特性,通过 props 控制外观,slot 管理内容,结合 CSS 实现视觉样式。






