背景:項目有用到 vue-echarts, 百度推出的 vue 版本的 Echarts,圖表自帶響應式屬性 auto-resize, 來實現窗口尺寸變化時,圖表的尺寸自適應,可是發現它是靠監聽 window 的 onresize 來實現的,而有時候當chart 容器 尺寸變化時,window 窗口大小是不變的,好比我此次遇到的,側邊菜單欄的顯示隱藏切換,致使內容區域總體部分寬度會變化,可是window 沒有變化,因此auto-resize 不能監聽這種狀況來實現 resize。javascript
解決思路:html
具體作法有如下幾種:vue
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id="demo" style="background: blue; height: 200px; width: 100%"> demo 內容 </div> <script> var observer = new MutationObserver(function (mutations, observer) { mutations.forEach(function (mutation) { console.log(mutation); }); }); var config = { attributes: true, attributeOldValue: true, attributeFilter: [ 'style' ] }; var el = document.getElementById('demo'); observer.observe(el, config); </script> </body> </html>
斟酌了上面幾種方案後,結合具體案例,我以爲仍是用 vuex 寫全局數據更好更方便一些,具體步驟以下java
// 注意的坑,1.要設置 width 2. width 變化有延遲,須要加個 timeout,否則看不到效果 this.$refs.chart.resize({width: this.$refs.chart.offsetWidth})