mixins.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /**
  2. * @param {Function} func
  3. * @param {number} wait
  4. * @param {boolean} immediate
  5. * @return {*}
  6. */
  7. function debounce(func, wait, immediate) {
  8. let timeout, args, context, timestamp, result
  9. const later = function () {
  10. // 据上一次触发时间间隔
  11. const last = +new Date() - timestamp
  12. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  13. if (last < wait && last > 0) {
  14. timeout = setTimeout(later, wait - last)
  15. } else {
  16. timeout = null
  17. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  18. if (!immediate) {
  19. result = func.apply(context, args)
  20. if (!timeout) context = args = null
  21. }
  22. }
  23. }
  24. return function (...args) {
  25. context = this
  26. timestamp = +new Date()
  27. const callNow = immediate && !timeout
  28. // 如果延时不存在,重新设定延时
  29. if (!timeout) timeout = setTimeout(later, wait)
  30. if (callNow) {
  31. result = func.apply(context, args)
  32. context = args = null
  33. }
  34. return result
  35. }
  36. }
  37. export default {
  38. data() {
  39. return {
  40. $_sidebarElm: null,
  41. $_resizeHandler: null
  42. }
  43. },
  44. mounted() {
  45. this.initListener()
  46. },
  47. activated() {
  48. if (!this.$_resizeHandler) {
  49. // avoid duplication init
  50. this.initListener()
  51. }
  52. // when keep-alive chart activated, auto resize
  53. this.resize()
  54. },
  55. beforeDestroy() {
  56. this.destroyListener()
  57. },
  58. deactivated() {
  59. this.destroyListener()
  60. },
  61. methods: {
  62. // use $_ for mixins properties
  63. // https://vuejs.org/v2/style-guide/index.html#Private-property-names-essential
  64. $_sidebarResizeHandler(e) {
  65. if (e.propertyName === 'width') {
  66. this.$_resizeHandler()
  67. }
  68. },
  69. initListener() {
  70. this.$_resizeHandler = debounce(() => {
  71. this.resize()
  72. }, 100)
  73. this.resize()
  74. window.addEventListener('resize', this.$_resizeHandler)
  75. // this.$_sidebarElm = document.getElementsByClassName('sidebar-container')[0]
  76. // this.$_sidebarElm && this.$_sidebarElm.addEventListener('transitionend', this.$_sidebarResizeHandler)
  77. },
  78. destroyListener() {
  79. window.removeEventListener('resize', this.$_resizeHandler)
  80. this.$_resizeHandler = null
  81. // this.$_sidebarElm && this.$_sidebarElm.removeEventListener('transitionend', this.$_sidebarResizeHandler)
  82. },
  83. resize() {
  84. const { chart } = this
  85. chart && chart.resize()
  86. }
  87. }
  88. }