echarts渲染完成事件finished/rendered

背景

  • 須要自適應大小
  • 須要loading加載。
  • 效果以下

NLKdGNKg7m.gif

echarts加載完成事件API

一、events. rendered

渲染結束事件。注意 rendered 事件並不表明渲染動畫(參見 animation 相關配置)或者漸進渲染(參見 progressive 相關配置)中止,只表明本幀的渲染結束。javascript

二、events. finished

渲染完成事件。當渲染動畫(參見 animation 相關配置)或者漸進渲染(參見 progressive 相關配置)中止時觸發。css

執行

咱們首先要在渲染以前打開loading
而後渲染完成以後關閉loading
渲染完成這裏選用的是finished事件html

  • 在vue中

templatevue

<div class="p-line-charts-out">
    <div v-show="!isLoading" class="p-line-charts" ref="lineCharts"></div> <!--圖表dom對象-->
    <dv-loading v-show="isLoading">Loading...</dv-loading> <!--loading組件-->
</div>
複製代碼

javascriptjava

//渲染前
this.isLoading = true

this.chart = this.$echarts.init(this.$refs.lineCharts)
//渲染後
this.chart.on('finished',_=>{
        this.isLoading = true
        console.log(113, 'finished')
})

複製代碼

scssweb

<style lang="scss" scoped>
.p-line-charts-out{
  height: 100%;
  width: 100%;
  .p-line-charts {
    width: 100%!important;
    height: calc(100% - 25px)!important;
  }
}
</style>
複製代碼
  • 可是finished事件有個問題,就是懸浮,點擊事件也會觸發鉤子函數

以下apache

AU8Gf1QMhw.gif

解決方法-1

若是 finished(rendered) 事件對你有用,那徹底能夠定義一個變量標識是否爲首次渲染,默認true,回調函數執行後,標識其爲false,解綁該事件再也不繼續執行相關代碼便可編程

const option = {...} //charts配置項

  let isFinished = false //標記 isFinished
  
  this.chart.on('finished',_=>{
    if(!isFinished){
      console.log('我只執行一次')
      isFinished = true
      this.isLoading = false //關閉loading
      this.chart.resize() //從新渲染charts大小
    }
    console.log(113, 'finished')
  })
  
  this.chart.setOption(option)
複製代碼

解決方法-2

利用異步編程promise,把完成後的動做放到異步隊列中api

const chartsPromise = new Promise(resolve => {
        const option = {...} //echarts配置

        this.chart = this.$echarts.init(this.$refs.lineCharts)

        this.chart.on('finished',_=>{ 
          resolve() //把執行結果拋出去
        })

        this.chart.setOption(option)
      })
      
      //promise resolve
      chartsPromise.then(_=>{
        this.isLoading = false//Loading標識關閉
        setTimeout(_=>{
          this.chart.resize() //宏任務隊列中切換echarts大小
        })
        console.log('渲染完成promise')
      })
      
複製代碼
相關文章
相關標籤/搜索