大致步骤:
- 实现组件基础结构和样式。
- 实现函数式调用组件方式和完成交互。
- 加上打开时动画效果。 给购物车删除加上确认框。
- 给vue挂载原型函数$confirm。
落地代码(confirm.vue):
实现组件基础结构和样式。
<template>
<div class="x-confirm">
<div class="wrapper">
<div class="header">
<h3>温馨提示</h3>
<a href="JavaScript:;" class="iconfont icon-close-new"></a>
</div>
<div class="body">
<i class="iconfont icon-warning"></i>
<span>您确认从购物车删除该商品吗?</span>
</div>
<div class="footer">
<Button size="mini" type="grey">取消</Button>
<Button size="mini" type="primary">确认</Button>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'XConfirm',
props: {
title: {
type: String,
default: '温馨提示'
},
text: {
type: String,
default: ''
},
submitCallback: {
type: Function
},
cancelCallback: {
type: Function
}
},
setup () {
const fade = ref(false)
onMounted(() => {
// 当元素渲染完毕立即过渡的动画不会触发
setTimeout(() => {
fade.value = true
}, 0)
})
return { fade }
}
}
</script>
<style scoped lang="less">
.x-confirm {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 8888;
background: rgba(0,0,0,.5);
.wrapper {
width: 400px;
background: #fff;
border-radius: 4px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
.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>
定义函数 confirm.js
import { createVNode, render } from 'vue'
import XConfirm from './confirm'
// 准备div
const div = document.createElement('div')
div.setAttribute('class', 'x-confirm-container')
document.body.appendChild(div)
// 该函数渲染XConfirm组件,标题和文本
// 函数的返回值是promise对象
export default ({ title, text }) => {
return new Promise((resolve, reject) => {
const submitCallback = () => {
render(null, div)
resolve()
}
const cancelCallback = () => {
render(null, div)
reject(new Error('点击取消'))
}
// 1. 渲染组件
// 2. 点击确认按钮,触发resolve同时销毁组件
// 3. 点击取消按钮,触发reject同时销毁组件
const vnode = createVNode(XConfirm, { title, text, submitCallback, cancelCallback })
render(vnode, div)
})
}
使用
Confirm({ text: '您确定删除吗?' }).then(() => {
console.log('点击确认')
}).catch(e => {
console.log('点击取消')
})
挂载全局
app.config.globalProperties.$confirm = Confirm