ant-design-vue中的modal组件没有afterOpen方法,导致第二次打开窗口时,由于容器宽度为0就加载了内部的组件,可能导致内部组件显示异常,例如下拉框的宽度。可以在modal组件内部添加一个辅助组件来解决这个问题。
辅助组件
size-container.vue
<template>
<div class="size-container" ref="containerRef">
<slot v-if="ready"></slot>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
let intervalId: NodeJS.Timeout | null
const ready = ref(false)
const containerRef = ref<HTMLDivElement | null>(null)
const emit = defineEmits<{
(e: 'show'): void
}>()
function checkContentSize() {
if (containerRef.value && containerRef.value.clientWidth > 0) {
if (intervalId) {
clearInterval(intervalId)
intervalId = null
}
ready.value = true
emit('show')
}
}
onMounted(() => {
intervalId = setTimeout(checkContentSize, 50)
})
onBeforeUnmount(() => {
if (intervalId != null) {
clearInterval(intervalId)
intervalId = null
}
})
</script>
<style lang="less" scoped>
.size-container {
position: relative;
width: 100%;
height: 100%;
display: block;
}
</style>
使用方法
demo-dialog.vue
<template>
<div>
<a-button type="primary" @click="showModal">Open Modal</a-button>
<a-modal v-model:open="open" title="Basic Modal" @ok="handleOk">
<SizeContainer @show="handleAfterOpen">
<p>Some contents...</p>
<p>Some contents...</p>
<p>Some contents...</p>
</SizeContainer>
</a-modal>
</div>
</template>
<script lang="ts" setup>
import SizeContainer from './size-container.vue'
import { ref } from 'vue'
const open = ref<boolean>(false)
const showModal = () => {
open.value = true
}
const handleOk = (e: MouseEvent) => {
console.log(e)
open.value = false
}
function handleAfterOpen() {}
</script>