Vue3自己封装 confirm 函数
一。 封装 confirm 组件 confirm.vue
<template>
<div class="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' size="mini" type="gray">取消</XtxButton>
<button @click='submitCallback' size="mini" type="primary">确认</XtxButton>
</div>
</div>
</div>
</template>
<script>
import { onMounted, ref, onUpdated } from 'vue'
export default {
name: 'Confirm',
props: {
title: {
type: String,
default: ''
},
text: {
type: String,
default: ''
},
cancelCallback: {
type: Function,
required: true
},
submitCallback: {
type: Function,
required: true
}
},
setup () {
const fade = ref(false)
onUpdated(() => {
console.log('----------xtx-confirm--------')
})
onMounted(() => {
setTimeout(() => {
fade.value = true
}, 0)
})
return { fade }
}
}
</script>
<style scoped lang="less">
.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: @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>
二,构建函数
import { createVNode, render } from 'vue'
const container = document.createElement('div')
container.setAttribute('class', 'confirm-container')
document.body.appendChild(container)
export default ({ title, text }) => {
return new Promise((resolve, reject) => {
const submitCallback = () => {
render(null, container)
resolve()
}
const cancelCallback = () => {
render(null, container)
reject('cancel')
}
const vnode = createVNode(XtxConfirm, { title, text, cancelCallback, submitCallback })
render(vnode, container)
})
}
三。操作按钮
<p><a @click='handleDelete(数据id)' class="green" href="javascript:;">删除</a></p>
import Confirm from 'confirm.js'
setup ( ){
const handleDelete = (数据id)=>{
Confirm({ title: '删除确认提示', text: '确认要删除该商品吗?' })
.then(() => {
return store.dispatch(, 数据id)
})
.then((ret) => {
Message({ text: ret, type: 'success' })
})
.catch((err) => {
if (err === 'cancel') return
Message({ text: err, type: 'error' })
})
}
}