封装confim组件
封装思路
- 创建confim组件
- props text,title
- 生成confim函数,confim函数返回一个promise,确认为resolve状态,取消为reject状态
组件代码
<template>
<div class="xtx-confirm" :class="{ fade }">
<div class="wrapper" :class="{fade}">
<div class="header">
<h3>{{ title }}</h3>
<a 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">
<xtxButton size="mini" type="gray" @click="cancel">取消</xtxButton>
<xtxButton size="mini" type="primary" @click="submit">确认</xtxButton>
</div>
</div>
</div>
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import xtxButton from './xtx-button.vue';
interface Props {
title?: string,
text?: string,
submitCallback: () => {},
cancelCallback: () => {}
}
const props = withDefaults(defineProps<Props>(), {
title: '温馨提示',
text: '您确认从购物车删除该商品吗'
})
const fade = ref(false)
const cancel = () => {
props.cancelCallback()
}
const submit = () => {
props.submitCallback()
}
onMounted(() => {
setTimeout(() => {
fade.value = true
}, 0);
})
</script>
<style scoped lang="less">
.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, .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: @priceColor;
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>
confim 函数代码
import { createVNode, render } from "vue";
import xtxConfirm from './xtx-confirm.vue'
// 创建一个content容器
const content = document.createElement("div");
// 设置容器的class
content.setAttribute('class','xtx-message-container')
// 将容器插入到body下
document.body.append(content)
interface Props {
title?:string,
text?:string
}
export default function({title,text}:Props) {
return new Promise((resolve,reject)=> {
// 点击确认按钮的回调
const submitCallback = ()=> {
render(null,content)
resolve('确定')
}
// 点击取消按钮的回调
const cancelCallback = ()=> {
render(null,content)
reject('取消')
}
// 将组件生成虚拟节点
// createVNode(组件,属性对象props)
const vNode = createVNode(xtxConfirm,{title,text,submitCallback,cancelCallback})
render(vNode,content)
})
}
使用
confim({ text: '您确认从购物车删除该商品吗??' }).then((res) => {
console.log(res)// 确认
},err=> {
console.log(err)// 取消
)