Toast.vue 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <template>
  2. <transition
  3. enter-active-class="fadeIn"
  4. leave-active-class="fadeOut"
  5. @after-leave="$emit('closed')"
  6. >
  7. <div
  8. v-if="visible"
  9. class="ptc-toast"
  10. :class="{ 'ptc-toast--loading': icon === 'loading' }"
  11. >
  12. <i v-if="icon !== 'none'" class="ptc-toast__icon"></i>
  13. <span class="ptc-toast__message">{{ message }}</span>
  14. </div>
  15. </transition>
  16. </template>
  17. <script setup lang="ts">
  18. import { getCurrentInstance, ref, watch } from 'vue'
  19. const props = withDefaults(
  20. defineProps<{
  21. visible: boolean
  22. message: string
  23. duration?: number
  24. icon?: 'loading' | 'none'
  25. }>(),
  26. {
  27. duration: 2000,
  28. icon: 'none',
  29. }
  30. )
  31. const emit = defineEmits<{
  32. (e: 'closed'): void
  33. (e: 'update:visible', val: boolean): void
  34. }>()
  35. let tid: NodeJS.Timeout
  36. const close = () => emit('update:visible', false)
  37. const reset = () => {
  38. clearTimeout(tid)
  39. if (props.duration) {
  40. tid = setTimeout(close, props.duration)
  41. }
  42. }
  43. watch(
  44. () => props.visible,
  45. val => val && reset()
  46. )
  47. watch(() => props.message, reset)
  48. </script>
  49. <style lang="scss">
  50. .ptc-toast {
  51. position: fixed;
  52. top: 50%;
  53. left: 50%;
  54. transform: translate(-50%, -50%);
  55. display: flex;
  56. flex-direction: column;
  57. align-items: center;
  58. justify-content: center;
  59. box-sizing: content-box;
  60. // hack for avoid max-width when use left & fixed
  61. min-width: 192px;
  62. max-width: 60%;
  63. width: fit-content;
  64. padding: 22px 38px;
  65. color: #fff;
  66. font-size: 28px;
  67. line-height: 40px;
  68. // allow newline charactor
  69. white-space: pre-wrap;
  70. text-align: center;
  71. word-wrap: break-word;
  72. background-color: rgba(0, 0, 0, 0.7);
  73. border-radius: 12px;
  74. z-index: 9999;
  75. &--loading {
  76. padding: 56px 24px 40px;
  77. }
  78. &__icon {
  79. margin-bottom: 32px;
  80. width: 64px;
  81. height: 64px;
  82. background-size: contain;
  83. .ptc-toast--loading & {
  84. background-image: url(@img/loading.svg);
  85. animation: rotate 1s linear infinite;
  86. }
  87. }
  88. }
  89. </style>