vue項目中使用window的onresize事件

vue項目中使用vue-echars繪製圖表時,需要實時根據窗口大小調整圖表的大小,我使用的auto-resize屬性,沒有作用,沒有找出錯誤在哪裏,使用window.onresize事件,必須銷燬纔不會報錯哦,代碼如下:

<template>
    <chart ref="chart1" :options="orgOptions"></chart>
</template>
<script>
export default {
  data() {
    return {
      orgOptions: {}
    };
  },

  created() {
    this.orgOptions = {
      xAxis: {
        type: "category",
        data: ""
      },
      yAxis: {
        type: "value"
      },
      series: [
        {
          data: "",
          type: "line"
        }
      ]
    };
  },
  mounted() {
    /*窗口自適應,關鍵代碼*/
    window.onresize = () => {
      this.$refs.chart1.resize();
    };
  },
    //註銷window.onresize事件
  destroyed() {
    window.onresize = null;
  }
}

注意:

1、window.onresize事件一般放在created或者mounted生命週期中。

2、window.onresize中的this指向的是window,不是指向vue,如果需要調用methods中的函數,需要在window.onresize事件的前面把指向vue的this賦值給其他字符,比如"_this";或者使用箭頭函數。

3、由於window.onresize是全局事件,在其他頁面改變界面時也會執行,這樣可能會出現問題,需要在出這個界面時註銷window.onresize事件。

4、window.onresize說明一個問題:beforeCreate、created、beforeMount、mounted、beforeUpdate、updated中的會觸發瀏覽器事件需要在destroyed、beforeDestory中銷燬掉。

 

發佈了14 篇原創文章 · 獲贊 5 · 訪問量 5399
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章