vue3+TS实战中Dialog弹窗封装复用技巧(修改和添加共用一个弹窗)涉及组件的传值(defineProps)和组件的自定义事件(emits)
<template>
<el-dialog
:title="dialogTitle"
:visible.sync="dialogVisible"
width="30%"
:before-close="handleClose"
>
<el-form :model="form" ref="dialogForm" label-width="80px">
<el-form-item label="名称">
<el-input v-model="form.name" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="描述">
<el-input type="textarea" v-model="form.description"></el-input>
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="submitForm">确 定</el-button>
</span>
</template>
</el-dialog>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
interface FormData {
name: string;
description: string;
}
export default defineComponent({
props: {
dialogVisible: {
type: Boolean,
default: false
},
dialogTitle: {
type: String,
default: ''
},
formData: {
type: Object as () => FormData,
default: () => ({ name: '', description: '' })
}
},
setup(props, { emit }) {
const form = ref<FormData>({ ...props.formData });
const handleClose = () => {
emit('update:dialogVisible', false);
};
const submitForm = () => {
emit('submit', form.value);
emit('update:dialogVisible', false);
};
return {
form,
handleClose,
submitForm
};
}
});
</script>
这个代码实例展示了如何在Vue 3和TypeScript中封装一个可复用的对话框组件。组件接收dialogVisible
(对话框显示状态)、dialogTitle
(对话框标题)和formData
(表单数据)作为props,并通过自定义submit
事件将表单数据发送给父组件。这样的设计使得添加和修改数据可以使用同一个对话框,减少了代码的重复和复杂度。
评论已关闭