由于考虑可维护性以及代码量的等问题,有时候就不能在一个页面里写太多的东西,适当的抽离出去会使页面更简洁,维护性也会高一些。今天就来讲一讲如何将el-dialog抽离出去。
示例代码
dialog页面
<template>
<div>
<el-dialog
:title="props.title"
:model-value="props.openDialog"
@close="confirmCancel"
:close-on-click-modal="false"
width="600"
>
<el-form :model="formData" ref="addRef">
<el-form-item
label="姓名"
prop="name"
label-width="120px"
>
<el-input
v-model="formData.name"
clearable
style="width: 300px"
/>
</el-form-item>
<el-form-item
label="年龄"
prop="age"
label-width="120px"
>
<el-input
v-model="formData.age"
clearable
style="width: 300px"
/>
</el-form-item>
</el-form>
<template #footer>
<div class="dialog-footer">
<el-button type="primary" @click="confirmSubmit">确 定</el-button>
<el-button @click="confirmCancel">取 消</el-button>
</div>
</template>
</el-dialog>
</div>
</template>
<script setup name="addDialog">
import {
computed, getCurrentInstance, reactive, ref, watch } from "vue";
const {
proxy } = getCurrentInstance();
const emits = defineEmits(["update:modelValue", "change","close"]);
const props = defineProps({
openDialog: {
type: Boolean,
default: false,
},
title: {
type: String,
},
});
// 弹出框标题
const title = ref(null);
// 是否显示弹出框
const openDialog = ref(false);
const addRef = ref(null);
// 表单数据
const formData = reactive({
name: null
age:null
});
// 确定
const confirmSubmit = () => {
confirmCancel();
emits("change", formData ); // 将事件以及表单的值抛出
};
// 取消
const confirmCancel = () => {
proxy.$refs["addRef"].resetFields(); // 清空表单
emits("close", false);
};
</script>
<style lang="scss" scoped>
</style>
引用dialog组件的页面
<template>
<div class="main-box">
....
<!-- 弹窗 -->
<addDialog
:openDialog.sync="openDialog"
:title="title"
@change="handleClick"
@close="closeClick"
></addDialog>
</div>
</template>
<script setup name="warning">
import {
computed, getCurrentInstance, onMounted, reactive, ref } from "vue";
import addDialog from "@/views/manage/addDialog.vue"; // 将弹窗组件引入
// 是否打开弹出框
const openDialog = ref(false);
// 弹出框标题
const title = ref(null);
// 表单数据
const formData = ref(null);
// 弹窗确定事件
const handleClick = (data) => {
formData.value = data; // 拿到弹窗抛出的值
openDialog.value = false; // 关闭弹窗
};
// 弹窗取消事件
const closeClick= (data) => {
openDialog.value = false;
};
</script>
<style scoped lang="scss">
</style>