Vue3全局封装modal弹框使用:
应用场景:全局动态form表单弹框
应用Vue3碎片: ref,reactive,app.component,defineExpose,defineProps,defineEmits
应用UI: element-plus dialog form
一.封装
1.引入
main.js
import App from './App.vue'
import ModalPanel from "@/components/element/ModalPanel.vue";
const app=createApp(App)
app.component('ModalPanel',ModalPanel)
2.使用
<ModalPanel
:defineWidth="defineWidth"
:selSingle="selSingle"
:editTitle="editTitle"
:editType="editType"
:editForm="editForm"
:fixedParam="fixedParam"
:randomParam="randomParam"
@updateData="declareData"
@updateShow="updateSingShow"
:key="modalPannelKey"
/>
开启
const openModalPannel = () => {
defineWidth.value=500;
editType.value="add";
editTitle.value="操作";
fixedParam.value=[
{ name:"XX",value:"name"},
];
randomParam.value=[
{ name:"xy",value:"name"},
];
}
关闭
const updateSingShow = () => {
selSingle.value=false;
}
接收
const declareData= (data) => {
//do...
}
二.具体封装
1.接收参数
const selSingleShow = ref(false);
const props = defineProps({
defineWidth: {
required: true,
type: Number,
default: 0,
},
selSingle: {
required: true,
type: Boolean,
default: "",
},
editTitle: {
required: true,
type: String,
default: "",
},
editType: {
required: true,
type: String,
default: "",
},
editForm: {
required: true,
type: Object,
default: {},
},
fixedParam: {
required: true,
type: Array,
default: [],
},
randomParam: {
required: true,
type: Array,
default: [],
},
});
const emit = defineEmits(['updateData','updateShow']);
const formList = reactive([]);
2.初始化值
onMounted(() => {
if(props!=undefined){
formList.push(...props.fixedParam);
formList.push(...props.randomParam);
selSingleShow.value=props.selSingle;
}
});
3.关闭弹框
const updateSingle=()=>{
emit("updateShow",selSingleShow);
}
4.更新数据
const updateNameChange=(data)=> {
emit("updateData",data);
}
5.弹框
<el-dialog
v-model="selSingleShow"
:title="editTitle"
:width="defineWidth"
align="left">
<div class="modal-padding">
<el-form
ref="ruleFormRef"
label-width="auto"
label-position="top"
:model="editForm"
:rules="rules"
class="demo-ruleForm"
>
<div v-for="(item, index) in formList">
<el-form-item :label="item.name" :prop="item.value">
<el-input v-model="editForm[item.value]" />
</el-form-item>
</div>
</el-form>
</div>
<template #footer>
<div class="modal-footer-padding">
<el-button type="primary"
>确认</el-button
>
<el-button >取消</el-button>
</div>
</template>
</el-dialog>
三,交互
1.组件暴露方法
import { ref, reactive, onMounted,defineExpose} from "vue";
defineExpose({
updateView,
});
2.引入页调用
const ModalRef= ref(null);
const ModalKey= ref(0);
<ModalPanel ref="ModalRef" :key="ModalKey"/>
刷新数据
if(ModalRef.value!=null){
ModalRef.value.updateViewList() //刷新数据
}
更新组件
ModalKey.value+= 1;