main.vue 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. <template>
  2. <transition name="el-message-fade" @after-leave="handleAfterLeave">
  3. <div
  4. :class="[
  5. 'el-message',
  6. type && !iconClass ? `el-message--${ type }` : '',
  7. center ? 'is-center' : '',
  8. showClose ? 'is-closable' : '',
  9. customClass
  10. ]"
  11. :style="positionStyle"
  12. v-show="visible"
  13. @mouseenter="clearTimer"
  14. @mouseleave="startTimer"
  15. role="alert">
  16. <i :class="iconClass" v-if="iconClass"></i>
  17. <i :class="typeClass" v-else></i>
  18. <slot>
  19. <p v-if="!dangerouslyUseHTMLString" class="el-message__content">{{ message }}</p>
  20. <p v-else v-html="message" class="el-message__content"></p>
  21. </slot>
  22. <i v-if="showClose" class="el-message__closeBtn el-icon-close" @click="close"></i>
  23. </div>
  24. </transition>
  25. </template>
  26. <script type="text/babel">
  27. const typeMap = {
  28. success: 'success',
  29. info: 'info',
  30. warning: 'warning',
  31. error: 'error'
  32. };
  33. export default {
  34. data() {
  35. return {
  36. visible: false,
  37. message: '',
  38. duration: 3000,
  39. type: 'info',
  40. iconClass: '',
  41. customClass: '',
  42. onClose: null,
  43. showClose: false,
  44. closed: false,
  45. verticalOffset: 20,
  46. timer: null,
  47. dangerouslyUseHTMLString: false,
  48. center: false
  49. };
  50. },
  51. computed: {
  52. typeClass() {
  53. return this.type && !this.iconClass
  54. ? `el-message__icon el-icon-${ typeMap[this.type] }`
  55. : '';
  56. },
  57. positionStyle() {
  58. return {
  59. 'top': `${ this.verticalOffset }px`
  60. };
  61. }
  62. },
  63. watch: {
  64. closed(newVal) {
  65. if (newVal) {
  66. this.visible = false;
  67. }
  68. }
  69. },
  70. methods: {
  71. handleAfterLeave() {
  72. this.$destroy(true);
  73. this.$el.parentNode.removeChild(this.$el);
  74. },
  75. close() {
  76. this.closed = true;
  77. if (typeof this.onClose === 'function') {
  78. this.onClose(this);
  79. }
  80. },
  81. clearTimer() {
  82. clearTimeout(this.timer);
  83. },
  84. startTimer() {
  85. if (this.duration > 0) {
  86. this.timer = setTimeout(() => {
  87. if (!this.closed) {
  88. this.close();
  89. }
  90. }, this.duration);
  91. }
  92. },
  93. keydown(e) {
  94. if (e.keyCode === 27) { // esc关闭消息
  95. if (!this.closed) {
  96. this.close();
  97. }
  98. }
  99. }
  100. },
  101. mounted() {
  102. this.startTimer();
  103. document.addEventListener('keydown', this.keydown);
  104. },
  105. beforeDestroy() {
  106. document.removeEventListener('keydown', this.keydown);
  107. }
  108. };
  109. </script>