antdv Modal(对话框)指定挂载节点 demo

今日需求

antdv Modal 挂载到指定位置


分析

antdv 的 Modal 默认是挂载在 body 上的
这就导致组件样式不能作用在 Modal 上, 解决办法就是把 Modal 挂载到组件以内的位置上

有问题找文档
果然, antdv 早就考虑到这种可能性, 并提供了指定挂载位置的 api

getContainer 指定 Modal 挂载的 HTML 节点

奈何文档并没有提供 demo
但根据解释的类型和默认值, 可以知道 getContainer 需要传入一个 function, 并 return 一个 html 的节点


解决问题

给目标节点设置 ref 属性
在 a-modal.getContainer传入一个方法, 方法根据 ref 返回目标节点

<template>
	<div ref="aff">
		<a-button type="primary" @click="showModal">
			Open Modal with async logic
		</a-button>
		<a-modal title="Title" :getContainer="getRefsAff" :visible="visible" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="handleCancel">
			<p>{
   
   { ModalText }}</p>
		</a-modal>
	</div>
</template>
<script type="text/javascript">
	export default {
     
     
		data() {
     
     
			return {
     
     
				ModalText: 'Content of the modal',
				visible: false,
				confirmLoading: false,
			};
		},
		methods: {
     
     
			getRefsAff() {
     
     
				return this.$refs.aff
			},
			showModal() {
     
     
				this.visible = true;
			},
			handleOk(e) {
     
     
				this.ModalText = 'The modal will be closed after two seconds';
				this.confirmLoading = true;
				setTimeout(() => {
     
     
					this.visible = false;
					this.confirmLoading = false;
				}, 2000);
			},
			handleCancel(e) {
     
     
				console.log('Clicked cancel button');
				this.visible = false;
			},
		},
	};
</script>

箭头函数写法

用箭头函数就更简单
给目标节点设置 ref 属性
在箭头函数里返回 $refs.aff

<template>
	<div ref="aff">
		<a-button type="primary" @click="showModal">
			Open Modal with async logic
		</a-button>
		<a-modal title="Title" :getContainer="() => $refs.aff" :visible="visible" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="handleCancel">
			<p>{
   
   { ModalText }}</p>
		</a-modal>
	</div>
</template>

以上内容基于 [email protected]

end

猜你喜欢

转载自blog.csdn.net/u013970232/article/details/115214570