fs-message.vue 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. <template>
  2. <view class="fs-message" :class="[{ show: state.options.show }, 'bg-' + state.options.type]">
  3. {{ state.options.message }}
  4. </view>
  5. </template>
  6. <script>
  7. /**
  8. * 消息通知组件
  9. * @description 消息通知组件
  10. */
  11. export default {
  12. name: 'fs-message'
  13. }
  14. </script>
  15. <script setup>
  16. import { reactive } from 'vue'
  17. const defaultOptions = {
  18. type: 'primary',
  19. duration: 3000
  20. }
  21. const state = reactive({
  22. options: {},
  23. timer: null
  24. })
  25. const formatOptions = options => {
  26. if (typeof options === 'string') {
  27. return {
  28. message: options
  29. }
  30. }
  31. if (options.type === 'error') {
  32. options.type = 'danger'
  33. }
  34. return options
  35. }
  36. const show = options => {
  37. state.options = {
  38. ...defaultOptions,
  39. ...formatOptions(options),
  40. show: true
  41. }
  42. if (state.timer) {
  43. clearTimeout(state.timer)
  44. }
  45. if (state.options.duration > 0) {
  46. state.timer = setTimeout(() => {
  47. handleHide()
  48. state.timer = null
  49. }, state.options.duration)
  50. }
  51. }
  52. const success = options => {
  53. show({
  54. ...formatOptions(options),
  55. type: 'success'
  56. })
  57. }
  58. const error = options => {
  59. show({
  60. ...formatOptions(options),
  61. type: 'danger'
  62. })
  63. }
  64. const warning = options => {
  65. show({
  66. ...formatOptions(options),
  67. type: 'warning'
  68. })
  69. }
  70. const info = options => {
  71. show({
  72. ...formatOptions(options),
  73. type: 'info'
  74. })
  75. }
  76. const handleHide = () => {
  77. state.options = {
  78. ...state.options,
  79. show: false
  80. }
  81. }
  82. defineExpose({
  83. show,
  84. success,
  85. error,
  86. warning,
  87. info,
  88. handleHide
  89. })
  90. </script>
  91. <style lang="scss" scoped>
  92. .fs-message {
  93. position: fixed;
  94. top: var(--window-top);
  95. left: 0;
  96. right: 0;
  97. padding: 20rpx;
  98. color: #fff;
  99. transition: all 0.1s;
  100. transform: translateY(-100%);
  101. text-align: center;
  102. z-index: 900;
  103. }
  104. .show {
  105. transform: translateY(0);
  106. }
  107. </style>