Ver código fonte

div容器尺寸监听

zhengnaiwen_citu 5 meses atrás
pai
commit
94396fcd27

+ 53 - 7
src/components/AutoComponents/ECharts/index.vue

@@ -1,5 +1,5 @@
 <template>
-  <div>
+  <div ref="content">
     <div class="tools"></div>
     <div :ref="id" class="chartBox"></div>
   </div>
@@ -8,29 +8,75 @@
 <script>
 import { generateUUID } from '@/utils'
 import EChartsComponent from './eCharts'
+// import elementResizeDetector from "element-resize-detector"
 export default {
   name: 'e-charts',
   data () {
     return {
       id: generateUUID(),
-      chart: null
+      chart: null,
+      resizeObserver: null
     }
   },
   beforeDestroy () {
-    window.removeEventListener('resize', this.onResize)
-    this.chart && this.chart.getEl().dispose()
+    this.cleanup()
+  },
+  mounted () {
+    this.setupResizeObserver()
   },
   methods: {
+    setupResizeObserver () {
+      if (!this.$refs.content) return
+
+      // if (ie11) {
+      //   this.resizeDetector = elementResizeDetector();
+      //   this.resizeDetector.listenTo(this.$refs.content, () => {
+      //     if (this.chart) {
+      //       this.onResize()
+      //     }
+      //   })
+      //   return
+      // }
+      this.resizeObserver = new ResizeObserver(() => {
+        if (this.chart) {
+          this.onResize()
+        }
+      })
+      this.resizeObserver.observe(this.$refs.content)
+    },
+    cleanup () {
+      window.removeEventListener('resize', this.onResize)
+      if (this.resizeObserver) {
+        // if (ie11) {
+        //   this.resizeDetector.removeListener(
+        //     this.$refs.content,
+        //     this.handleResize
+        //   )
+        // }
+        this.resizeObserver.disconnect() // 停止监听
+        this.resizeObserver = null
+      }
+      if (this.chart) {
+        this.chart.getEl().dispose()
+        this.chart = null
+      }
+    },
+    setRect () {
+      this.$refs[this.id].style.width = this.$refs.content.offsetWidth + 'px'
+      this.$refs[this.id].style.height = this.$refs.content.offsetHeight + 'px'
+    },
     onInit () {
       // 注册必须的组件
       this.chart = new EChartsComponent(this.$refs[this.id])
-      this.$refs[this.id].style.width = this.$refs[this.id].offsetWidth + 'px'
-      this.$refs[this.id].style.height = this.$refs[this.id].offsetHeight + 'px'
+      this.setRect()
       window.addEventListener('resize', this.onResize)
       return this.chart.getEl()
     },
     onResize () {
-      this.chart.getEl().resize()
+      this.$nextTick(() => {
+        this.setRect()
+        this.chart.getEl().resize()
+      })
     }
   }
 }

+ 6 - 0
src/styles/index.scss

@@ -53,6 +53,12 @@ $max-classes: 10;
   }
 }  
 
+$baseSize: 1px;
+@for $i from 0 through 40 {
+  .font-#{$i} {
+    font-size: $i * $baseSize !important;
+  }
+}
 
 .cursor-pointer {
   cursor: pointer;