封装一个confirm的函数组件
- 创一个文件夹专门放函数组件
- 把组件的样式写好
<template>
<div class="xtx-confirm" :class='{ fade: fade }'>
<div class="wrapper" :class='{ fade: fade }'>
<div class="header">
<h3>{{title}}</h3>
<a @click='cancelCallback' href="JavaScript:;" class="iconfont icon-close-new"></a>
</div>
<div class="body">
<i class="iconfont icon-warning"></i>
<span>{{text}}</span>
</div>
<div class="footer">
<button @click='cancelCallback' class="btn">取消</button>
<button @click='submitCallback' class="btn">确认</button>
</div>
</div>
</div>
</template>
<script lang="ts" setup>
import {
onMounted,
ref,
onUpdated
} from 'vue'
type Props = {
title: String,
text: String,
cancelCallback: () => void,
submitCallback: () => void
}
const props = defineProps < Props > ()
const fade = ref(false)
onUpdated(() => {
console.log('----------xtx-confirm--------')
})
onMounted(() => {
setTimeout(() => {
fade.value = true
}, 0)
})
</script>
<style scoped lang="less">
.fade {
background: #000;
}
.btn{
padding:3px 10px;
margin-left: 5px;
}
.xtx-confirm {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 8888;
background: rgba(0, 0, 0, 0);
&.fade {
transition: all 0.4s;
background: rgba(0, 0, 0, 0.5);
}
.wrapper {
width: 400px;
background: #fff;
border-radius: 4px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -60%);
opacity: 0;
&.fade {
transition: all 0.4s;
transform: translate(-50%, -50%);
opacity: 1;
}
.header,
.footer {
height: 50px;
line-height: 50px;
padding: 0 20px;
}
.body {
padding: 20px 40px;
font-size: 16px;
.icon-warning {
color: yellowgreen;
margin-right: 3px;
font-size: 16px;
}
}
.footer {
text-align: right;
.xtx-button {
margin-left: 20px;
}
}
.header {
position: relative;
h3 {
font-weight: normal;
font-size: 18px;
}
a {
position: absolute;
right: 15px;
top: 15px;
font-size: 20px;
width: 20px;
height: 20px;
line-height: 20px;
text-align: center;
color: #999;
&:hover {
color: #666;
}
}
}
}
}
</style>
- 用createVNode和render创建渲染组件 用Promise封装 可以用then 和catch调用点击确认和取消
`javascript
import { createVNode, render } from 'vue';
import Confirm from './confirm.vue';
const container = document.createElement('div')
document.body.append(container)
type Props = {
title: String,
text: String,
}
export default ({ title, text }: Props) => {
return new Promise<void>((resolve, reject) => {
const submitCallback = () => {
render(null, container)
resolve()
}
const cancelCallback = () => {
render(null, container)
reject('取消')
}
const vNode = createVNode(Confirm, { title, text, submitCallback, cancelCallback })
render(vNode, container)
})
}
- 在组件中用函数调用组件
<template>
<div @click="doConfirm">点机打开confirm</div>
</template>
<script setup lang='ts'>
import Confirm from './render/confirm.js';
const doConfirm = () => {
Confirm({
title: '标题来啦',
text: '内容来啦'
}).then((res)=>{
console.log('成功了');
}).catch((err)=>{
console.log(err);
})
}
</script>