在業(yè)務(wù)中沐飘,我們經(jīng)常會遇到各種各樣的彈窗組件稳衬,一般我們都是直接將其封裝成一個組件瘟忱,通過v-model
或者v-if
之類的手段進(jìn)行控制, But 很容易就出現(xiàn)下面這種情況
<DetailModal v-model="detailVisible" />
<ConfirmModal v-model="confirmVisible" />
<BindModal v-model="bindVisible />
現(xiàn)上述這種情況香缺,我們需要同時維護(hù)多個彈窗的隱藏顯示手销,然后要寫很多個 toggle BalaBala。 于是乎图张, 我們可以看到很多UI框架的封裝Modal都提供了函數(shù)調(diào)用的形式锋拖,直接通過函數(shù)就可以控制彈窗。
this.$Modal.confirm({
content: '詳情彈窗‘
})
上述的方式祸轮,我們可以更加簡潔地維護(hù)彈窗狀態(tài)兽埃,而不用去同時維護(hù)對應(yīng)的html和狀態(tài),簡單看下下面的sample
import Vue, { CreateElement } from "vue";
import { Button } from "view-design";
let Instance!: any;
export default function deleteModal(props: any) {
if (!Instance) {
Instance = new Vue({
data() {
return {
visible: false,
onOk: () => {},
loading: false,
title: ""
};
},
methods: {
show(options: any) {
Instance.visible = true;
Instance.onOk = options.onOk;
Instance.loading = options.loading;
Instance.title = options.title;
Instance.content = options.content;
}
},
render(this: any, h: CreateElement) {
const okButton = (scope: any) =>
h(
Button,
{
props: {
type: "error",
ghost: true,
loading: this.loading
},
slot: "ok",
on: {
click: () => {
this.onOk(scope.close);
}
}
},
["刪除"]
);
return h(
"Modal",
{
props: {
...props,
content: [],
title: this.title,
value: this.visible
},
on: {
input: (status: boolean) => {
this.visible = status;
}
},
scopedSlots: {
ok: okButton
}
},
[this.content]
);
}
});
const component = Instance.$mount();
document.body.appendChild(component.$el);
const modal = Instance.$children[0];
}
Instance.show(props);
return Instance;
}
上述的Sample的場景是刪除提示的按鈕, 通過 deleteModal
的方式我們就可以調(diào)用起對應(yīng)的窗口, 而不需要在父組件中定義相關(guān)的彈窗組件,
其主要原因是通過Vue.$mount
獲取到對應(yīng)組件的dom元素,直接掛載到docume.body上, 通過控制實例來執(zhí)行相關(guān)的操作, 但以上的代碼還有很多需要改進(jìn)的地方,
待續(xù)...