vue抽屉组件实现
Vue 抽屉组件实现
使用 Element UI 实现抽屉组件
安装 Element UI 库:
npm install element-ui
在 main.js 中引入 Element UI:
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
在组件中使用抽屉:
<template>
<div>
<el-button @click="drawer = true" type="primary">打开抽屉</el-button>
<el-drawer
title="标题"
:visible.sync="drawer"
direction="rtl"
size="50%">
<span>抽屉内容</span>
</el-drawer>
</div>
</template>
<script>
export default {
data() {
return {
drawer: false
}
}
}
</script>
使用 Ant Design Vue 实现抽屉组件
安装 Ant Design Vue:
npm install ant-design-vue
在 main.js 中引入 Ant Design Vue:
import Vue from 'vue';
import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
Vue.use(Antd);
在组件中使用抽屉:
<template>
<div>
<a-button type="primary" @click="showDrawer">打开抽屉</a-button>
<a-drawer
title="标题"
placement="right"
:closable="false"
:visible="visible"
@close="onClose"
width="50%">
<p>抽屉内容</p>
</a-drawer>
</div>
</template>
<script>
export default {
data() {
return {
visible: false
}
},
methods: {
showDrawer() {
this.visible = true
},
onClose() {
this.visible = false
}
}
}
</script>
自定义实现抽屉组件
创建自定义抽屉组件 Drawer.vue:
<template>
<transition name="fade">
<div class="drawer" v-if="visible">
<div class="drawer-mask" @click="close"></div>
<div class="drawer-content" :style="{width: width}">
<div class="drawer-header">
<h3>{{title}}</h3>
<button @click="close">×</button>
</div>
<div class="drawer-body">
<slot></slot>
</div>
</div>
</div>
</transition>
</template>
<script>
export default {
props: {
visible: Boolean,
title: String,
width: {
type: String,
default: '30%'
}
},
methods: {
close() {
this.$emit('update:visible', false)
}
}
}
</script>
<style scoped>
.drawer {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1000;
}
.drawer-mask {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
}
.drawer-content {
position: absolute;
right: 0;
top: 0;
bottom: 0;
background-color: #fff;
box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
}
.drawer-header {
padding: 16px;
border-bottom: 1px solid #f0f0f0;
display: flex;
justify-content: space-between;
align-items: center;
}
.drawer-body {
padding: 16px;
}
.fade-enter-active, .fade-leave-active {
transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
使用自定义抽屉组件:
<template>
<div>
<button @click="showDrawer">打开抽屉</button>
<Drawer
v-model="visible"
title="自定义抽屉"
width="40%">
<p>这是自定义抽屉内容</p>
</Drawer>
</div>
</template>
<script>
import Drawer from './Drawer.vue'
export default {
components: { Drawer },
data() {
return {
visible: false
}
},
methods: {
showDrawer() {
this.visible = true
}
}
}
</script>
抽屉组件的关键特性
- 动画效果:使用 Vue 的 transition 组件实现平滑的打开和关闭动画
- 遮罩层:点击遮罩层可以关闭抽屉,提升用户体验
- 自定义宽度:通过 props 可以灵活设置抽屉的宽度
- 插槽支持:通过 slot 可以插入任意内容
- 双向绑定:使用 v-model 简化状态管理







