最近在做一个前端页面,使用的vue3+ant-design-vue的技术栈,项目中需要使用modal弹窗,默认的modal背景是普通白色,想把它改成和网站界面相似的渐变色背景,却始终选不中,后来找了很多方法才找到正确的方法。
ant-design-vue中的弹窗modal
modal可以在当前页面中打开一个窗口浮层。https://antdv.com/components/modal-cn。一个默认的代码和样式是:
<template>
<div>
<a-button type="primary" @click="showModal">Open Modal</a-button>
<a-modal v-model:open="open" title="Basic Modal" @ok="handleOk">
<p>Some contents...</p>
<p>Some contents...</p>
<p>Some contents...</p>
</a-modal>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
const open = ref<boolean>(false);
const showModal = () => {
open.value = true;
};
const handleOk = (e: MouseEvent) => {
console.log(e);
open.value = false;
};
</script>
这段代码是一个简单的例子。会创建一个按钮,点击会打开一个弹窗。
可以看到,默认弹窗样式其实还可以,但是根据需求还是要改一改。
为什么使用:deep等方式无法选中modal中的元素
为了改背景色,需要选中下图中的ant-modal-content、ant-modal-header、ant-modal-body等改变其背景色,但是直接对其通过style、background、:deep等方式修改背景色,结果发现都无法选中。
这是为什么呢,后来发现有一个说法比较可靠:modal是挂载在和app同级路径下的,层级很高,所以使用:deep方式无法选中,有说使用:global的,但是我没有成功。
那怎么选中呢
在modal中有一个getContainer的接口,可以指定modal挂载的节点。
把modal挂载到当前页面的一个div下,然后使用这个div的:deep就能选中了。
<template>
<div ref="modal" class="cust-modal">
<a-button type="primary" @click="showModal">Open Modal</a-button>
<a-modal
v-model:open="open"
title="Basic Modal"
:getContainer="() => $refs.modal"
@ok="handleOk"
>
<p>Some contents...</p>
<p>Some contents...</p>
<p>Some contents...</p>
</a-modal>
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
const open = ref<boolean>(false);
const showModal = () => {
open.value = true;
};
const handleOk = (e: MouseEvent) => {
console.log(e);
open.value = false;
};
</script>
<style scoped>
.cust-modal :deep(.ant-modal-content) {
background: red;
}
.cust-modal :deep(.ant-modal-header) {
background: yellow;
}
</style>