cl-toast.vue 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. <template>
  2. <view class="cl-toast__wrap">
  3. <template v-for="(item, index) in list">
  4. <view
  5. class="cl-toast"
  6. v-if="!item.closed"
  7. :key="item.id"
  8. :class="[
  9. `cl-toast--${item.type}`,
  10. `is-${item.position}`,
  11. item.visible ? 'is-show' : '',
  12. item.icon ? 'is-icon' : '',
  13. ]"
  14. >
  15. <view class="cl-toast__icon" v-if="item.icon">
  16. <cl-icon :name="`cl-icon-toast-${item.icon}`"></cl-icon>
  17. </view>
  18. <slot>
  19. <text class="cl-toast__content">{{ item.message }}</text>
  20. </slot>
  21. </view>
  22. </template>
  23. </view>
  24. </template>
  25. <script>
  26. import { isObject, isString, isFunction } from "../../utils";
  27. let id = 0;
  28. /**
  29. * toast 吐司提示
  30. * @description 吐司提示
  31. * @tutorial https://docs.cool-js.com/uni/components/feedback/toast.html
  32. * @property {Boolean} single 是否单个显示,默认false
  33. * @example <cl-toast ref="toast"></cl-toast>
  34. */
  35. export default {
  36. name: "cl-toast",
  37. props: {
  38. // 是否单个显示
  39. single: Boolean,
  40. },
  41. data() {
  42. return {
  43. list: [],
  44. };
  45. },
  46. methods: {
  47. open(d) {
  48. // 默认配置
  49. let options = {
  50. id: id++,
  51. visible: false,
  52. closed: false,
  53. icon: "",
  54. message: "",
  55. duration: 2000,
  56. type: "default",
  57. position: "bottom",
  58. timer: null,
  59. onClose: null,
  60. iconSize: 22,
  61. };
  62. // 合并参数
  63. if (isObject(d)) {
  64. Object.assign(options, d);
  65. } else {
  66. options.message = d;
  67. }
  68. // 是否同时存在多个提示
  69. if (this.single) {
  70. this.list = [options];
  71. } else {
  72. this.list.push(options);
  73. }
  74. setTimeout(() => {
  75. this.create(options);
  76. }, 50);
  77. },
  78. close(item) {
  79. // 清空计时器
  80. clearTimeout(item.timer);
  81. item.visible = false;
  82. // 关闭回调
  83. if (isFunction(item.onClose)) {
  84. item.onClose(this);
  85. }
  86. setTimeout(() => {
  87. item.closed = true;
  88. }, 300);
  89. },
  90. create(item) {
  91. const { duration } = item || {};
  92. if (duration > 0) {
  93. item.visible = true;
  94. item.timer = setTimeout(() => {
  95. this.close(item);
  96. }, duration);
  97. }
  98. },
  99. },
  100. };
  101. </script>