ant design vue抽屉和表单结合封装成子组件,父组件控制显隐
时间: 2023-08-22 22:04:28 浏览: 175
好的,您可以这样封装:
```vue
<template>
<a-drawer
:visible="visible"
:mask-closable="false"
:closable="false"
:width="420"
@close="onClose"
>
<slot></slot>
<div class="drawer-footer">
<a-button style="margin-right: 8px;" @click="onClose">取消</a-button>
<a-button type="primary" :loading="submitting" @click="onSubmit">
提交
</a-button>
</div>
</a-drawer>
</template>
<script>
import { Drawer, Button } from 'ant-design-vue';
export default {
name: 'MyDrawer',
components: {
'a-drawer': Drawer,
'a-button': Button,
},
props: {
visible: {
type: Boolean,
default: false,
},
},
data() {
return {
submitting: false,
};
},
methods: {
onClose() {
this.$emit('update:visible', false);
},
onSubmit() {
this.submitting = true;
// 处理表单提交逻辑
this.$emit('submit', () => {
this.submitting = false;
this.onClose();
});
},
},
};
</script>
<style>
.drawer-footer {
display: flex;
justify-content: flex-end;
align-items: center;
height: 56px;
border-top: 1px solid #e8e8e8;
padding: 0 16px;
}
</style>
```
然后在父组件中使用:
```vue
<template>
<div>
<a-button type="primary" @click="visible = true">
打开抽屉
</a-button>
<my-drawer :visible.sync="visible" @submit="onSubmit">
<a-form :form="form">
<a-form-item label="姓名" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
<a-input v-model="form.name" />
</a-form-item>
<a-form-item label="年龄" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
<a-input-number v-model="form.age" />
</a-form-item>
</a-form>
</my-drawer>
</div>
</template>
<script>
import MyDrawer from './MyDrawer.vue';
import { Form, Input, InputNumber } from 'ant-design-vue';
export default {
components: {
MyDrawer,
'a-form': Form,
'a-form-item': Form.Item,
'a-input': Input,
'a-input-number': InputNumber,
},
data() {
return {
visible: false,
form: {
name: '',
age: undefined,
},
};
},
methods: {
onSubmit(callback) {
this.$refs.form.validate(async (valid) => {
if (!valid) {
return;
}
// 处理表单提交逻辑
await this.$api.submitForm(this.form);
callback();
});
},
},
};
</script>
```
这样,您就可以在父组件中通过控制 `visible` 来控制抽屉的显隐,并且抽屉中的表单数据可以通过 `submit` 事件提交到父组件中进行处理。
阅读全文