src/components/XtxMessage/type.d.ts
export type MessageType = 'success' | 'error' | 'warning'
export type Message = {
type: MessageType
text: string
duration?: number
}
src/components/XtxMessage/index.ts
// 导入XtxMessage.vue组件
// 通过代码的方式去渲染它
import { h, render } from 'vue'
import { Message } from './type'
import XtxMessage from './XtxMessage.vue'
// 创建一个dom容器
// 把这个容器添加在body上
const div = document.createElement('div')
div.className = "xtx-message-container"
document.body.appendChild(div)
// 调用这个函数
let timer = -1
export default function Message(obj: Message){
const vNode = h(XtxMessage, { type: obj.type, text: obj.text})
// 把虚拟dom放入上面定义的容器中
render(vNode, div)
clearTimeout(timer)
// 开启定时器,删除
timer = window.setTimeout(() => {
// 从dom上删除
render(null, div)
}, obj.duration||2000)
}
Message.success = (value: string) => {
Message({ type: "success", text: value, duration: 1500})
}
Message.error = (value: string) => {
Message({ type: "error", text: value, duration: 1500})
}
Message.warning = (value: string) => {
Message({ type: "warning", text: value, duration: 1500})
}
此时
src/components/XtxMessage/XtxMessage.vue
<script lang="ts" setup name="XtxMessage">
import { MessageType } from './type'
import { ref, onMounted } from 'vue'
defineProps<{
type: MessageType
text: string
}>()
// 定义一个对象,包含三种情况的样式,对象key就是类型字符串
const style = {
warning: {
icon: 'icon-warning',
color: '#E6A23C',
backgroundColor: 'rgb(253, 246, 236)',
borderColor: 'rgb(250, 236, 216)',
},
error: {
icon: 'icon-shanchu',
color: '#F56C6C',
backgroundColor: 'rgb(254, 240, 240)',
borderColor: 'rgb(253, 226, 226)',
},
success: {
icon: 'icon-queren2',
color: '#67C23A',
backgroundColor: 'rgb(240, 249, 235)',
borderColor: 'rgb(225, 243, 216)',
},
}
// 初始隐藏
const isShow = ref(false)
// dom渲染完成,显示
onMounted(() => {
isShow.value = true
})
</script>
<template>
<Transition name="down">
<div class="xtx-message" :style="style[type]" v-show="isShow">
<i class="iconfont" :class="style[type].icon"></i>
<span class="text">{{text}}</span>
</div>
</Transition>
</template>
<style scoped lang="less">
.down-enter-from {
transform: translateY(-70px);
}
.down-enter-active {
transition: transform 0.5s;
}
.xtx-message {
width: 300px;
height: 50px;
position: fixed;
z-index: 9999;
left: 50%;
margin-left: -150px;
top: 25px;
line-height: 50px;
padding: 0 25px;
border: 1px solid #e4e4e4;
background: #f5f5f5;
color: #999;
border-radius: 4px;
i {
margin-right: 4px;
vertical-align: middle;
}
.text {
vertical-align: middle;
}
}
</style>
注解:
在vue中,显示隐藏,创建移除,一个元素或者一个组件的时候,可以通过transition实现动画。
- 进入(显示,创建)
- v-enter-from 进入前
- v-enter-to 进入后
- v-enter-active 进入中
- 离开(隐藏,移除)
- v-leave-from 进入前
- v-leave-active 进入中
- v-leave-to 进入后
多个transition使用不同动画,可以添加nam属性,name属性的值替换v即可。
使用时,就直接导入 Message. 就会有提示