Vue3 消息提示组件封装

423 阅读1分钟

实现一个简易的 Message 消息组件,包含类型有警告(warning)、成功(success)、失败(error)。

封装一个Message组件:

<script lang="ts" setup name="Message">
import { onMounted, ref } from 'vue'
import { MessageType } from './type';

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="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 .5s;
}

.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>

为Message定义类型:

export type MessageType = 'success' | 'error' | 'warning'
export type Message = {
  type: MessageType
  text: string
  duration: number
}

封装:

// 导入Message.vue组件
// 通过代码的方式去渲染它

import { h, render } from 'vue'
import { Message } from './type'

import Messages from './Message.vue'

// 创建一个dom容器
// 把这个容器添加在body上
const div = document.createElement('div')
div.className = "message-container"
document.body.appendChild(div)


// 调用这个函数
let timer = -1
export default function Message(obj: Message){
  const vNode = h(Messages, { 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})
}

最后注册:

// 统一的注册所有的全局组件
import Message from './Message/Message.vue'
// App 是在vue库中定义好的类型
import { App } from 'vue'
export default {
  install (app: App) {
    app.component('Message', Message)
  }
}

组件结构:

image.png

在需要时导入Message组件即可使用。

    Message.success('你好帅哦')

image.png