应用场景
在使用ant-design-vue样式框架时,经常会用到弹框,有时一个页面可能会弹出多个不同风格弹框,那么如何去对不同的弹框进行样式处理,并且彼此之间不冲突呢?
解决方法
modal弹框,最终的显示不是在当前页面,而是在最外层的页面。和绑定app的div平级。这里要注意,如果是在父级页面使用,那么不需要样式穿透;如果实在子页面使用,并且添加限制在当前页面有效时,就要添加样式穿透的效果。
在调整弹框内部的样式时,我们需要了解modal内部的结构,如下图:
bodyStyle 对应的div:.ant-modal-body 所在的div
style 对应的div: .ant-modal 所在的div
ant-modal-content 对应的样式
footer 对应的div .ant-modal-footer 所在的div
header 对应的div .ant-modal-header 所在的div
<template>
<div class="practice" style="margin:0 auto;">
<!--自定义底部样式-->
<a-modal width="960px" class="overTime" :placement="placement" bodyStyle="padding:0;border-radius:10px;"
style="font-size: 32px;" :closable="false" :visible="expirationVisible" @cancel="onClose">
<!--自定义头部样式-->
<template #title>
<div>ant-modal-header</div>
</template>
<div class="expirationTips">
ant-modal-body
</div>
<!--自定义底部样式-->
<template #footer>
<a-space>
<a-button type="default" @click="onClose"> ant-modal-footer </a-button>
</a-space>
</template>
</a-modal>
</div>
</template>
<script setup >
import { ref, onBeforeMount, onMounted } from 'vue';
const expirationVisible = ref(true)
const onClose = () => {
expirationVisible.value = false
}
</script>
<style lang="less" scoped >
.expirationTips {
width: 100%;
height: 368px;
}
//当不存在 scoped 时样式生效,当存在时,该样式不生效
.overTime {
background: green;
//内容
.ant-modal-content {
background: red;
padding: 20px;
//头部
.ant-modal-header {
background: pink;
}
//中心内容
.ant-modal-body {
background: yellow;
}
//底部按钮
.ant-modal-footer {
background: blue;
}
}
:global(.ant-modal-content){
padding: 20px;
background: red;
}
//当存在scoped时生效
:global(.ant-modal-header) {
background: pink;
margin-top: 10px;
}
:global(.ant-modal-body) {
margin-top: 10px;
background: yellow;
}
:global(.ant-modal-footer) {
margin-top: 10px;
background: blue;
}
}
</style>
遇到的问题
1、存在 scoped 时,内部的样式调整不动?
因为modal所在的层级和和app所在的div同级,所以,当scoped存在是,直接调用是不生效的,而且不能用deep进行深度选择,只能用global。
2、如何自定义头部的标题?
可以使用<template #title><div>ant-modal-header</div></template>,具体的使用方法,可以看代码案例
3、如何自定义底部的按钮?
运用插槽的方式,将#footer里面的内容进行重新定义。
4、vue3 样式穿透的写法?
deep: :deep(类名){样式属性}
global: :global(类名){样式属性}
5、深度选择器 deep 和 全局选择器 global 的区别?
主要是两个穿透的方向不一样,deep 是向下级穿透,修改当前页面的组件内的样式;而global是全局的,范围更大,也可以向上级穿透,如是使用modal时,就只能用global,而不能用deep.
总结分享
以前工作之余,空闲的时间都会去刷抖音、快手,看看微信公众号,而没有想着如何去提升自己;而在阅读《认知觉醒》以后,就在思考,如何将复杂的事情简单做,简单的事情快速做,非必要的事情安排别人做,将更多的时间用来提升自我。