样式分析
- 1.弹框组件最上层是标题 可以动态绑定属性 这边绑定名称设置为title
- 2.右上角x按钮在父组件用v-model="visible"双向绑定 设置visible为boolean值 把值传递给子组件实现双向绑定 从子组件抛出boolean实现关闭和打开
- 3.中间内容用
<slot>默认插槽来实现自定义内容 - 4.底部 确认取消
<slot name="footer"><slot/>具名插槽来实现自定义按钮
定义基础布局
class="xtx-dialog" 样式是遮罩层样式......
class="wrapper" 是弹窗样式....
<template>
<div class="xtx-dialog">
<div class="wrapper">
<div class="header">
<h3>切换收货地址</h3>
<a href="JavaScript:;" class="iconfont icon-close-new"></a>
</div>
<div class="body">对话框内容</div>
<div class="footer">
<XtxButton type="gray" style="margin-right: 20px">取消</XtxButton>
<XtxButton type="primary">确认</XtxButton>
</div>
</div>
</div>
</template>
<style scoped lang="less">
.xtx-dialog {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 8887;
background: rgba(0, 0, 0, 0.5);
// background: rgba(0, 0, 0, 0);
// &.fade {
// transition: all 0.4s;
// background: rgba(0, 0, 0, 0.5);
// }
.wrapper {
width: 600px;
background: #fff;
border-radius: 4px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
// transform: translate(-50%, -60%);
// opacity: 0;
// &.fade {
// transition: all 0.4s;
// transform: translate(-50%, -50%);
// opacity: 1;
// }
.body {
padding: 20px 40px;
font-size: 16px;
.icon-warning {
color: @priceColor;
margin-right: 3px;
font-size: 16px;
}
}
.footer {
text-align: center;
padding: 10px 0 30px 0;
}
.header {
position: relative;
height: 70px;
line-height: 70px;
padding: 0 20px;
border-bottom: 1px solid #f5f5f5;
h3 {
font-weight: normal;
font-size: 18px;
}
a {
position: absolute;
right: 25px;
top: 25px;
font-size: 24px;
width: 20px;
height: 20px;
line-height: 20px;
text-align: center;
color: #999;
&:hover {
color: #666;
}
}
}
}
}
</style>
动态绑定基础布局属性
import { onClickOutside } from '@vueuse/core'
import { ref } from 'vue';
// 格式:onClickOutside(dom元素,回调)
// 作用:当在 {dom元素} 之外点击,执行{回调}
const target = ref(null)
onClickOutside(target, () => {
close()
})
defineProps<{
title: string,
modelValue: boolean
}>()
const emit = defineEmits<{
(e: 'update:modelValue', val: boolean) : void
}>()
// v-model="visible"
// :modelValue + @update:modelValue
const close = () => {
// 抛出事件 @update:modelValue
emit('update:modelValue', false)
}
</script>
<template>
<!-- // teleport是v3中提供新的内置组件 -->
<!-- 作用;将其中的元素挂载到指定的dom上 -->
<teleport to="body">
<div class="xtx-dialog" v-show="modelValue">
<div class="wrapper" ref="target">
<div class="header">
<h3>{{title}}</h3>
<a href="JavaScript:;" @click="close" class="iconfont icon-close-new"></a>
</div>
<div class="body">
<slot/>
</div>
<div class="footer">
<slot name="footer">
<XtxButton type="gray" style="margin-right: 20px">取消</XtxButton>
<XtxButton type="primary">确认</XtxButton>
</slot>
</div>
</div>
</div>
</teleport>
</template>
使用组件
<button @click="visible=!visible">点击</button>
<XtxDialog title="什么样子标题" v-model="visible">
<div>
内容
</div>
<template #footer>
<button>按钮</button>
</template>
</XtxDialog>
里面内容可以根据需要自定义