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
-
- <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实现动画。

多个transition使用不同动画,可以添加nam属性,name属性的值替换v即可。
使用时,就直接导入 Message. 就会有提示