vue中引入echarts渲染問題

1.經過如下命令安裝echartshtml

npm install echarts --save

2.在main.js文件裏全局引入echartsnpm

import echarts from 'echarts'
Vue.prototype.$echarts = echarts

3.單頁面引用echartsecharts

import echarts from 'echarts'
// html代碼
<div v-if="noData">123</div>
<div v-else class="details-ECharts" style="width:100%;overflow-x: scroll;">
  <div id="myECharts" style="width:100%;height:220px;background-color:#ffffff;"></div>
</div>
<script>
// js代碼
import echarts from 'echarts'
export default {
  name: 'aaa',
  data () {
    return {
      xData: [],
      tionData: [],
      noData: false
    }
  },
  methods: {
    // echarts渲染
    statistics () {
      var myChart
      myChart = echarts.init(document.getElementById('myECharts'))
      myChart.setOption({
        title: {
          text: '對比圖',
          x: 'center',
          y: 'bottom',
          textStyle: {
            color: '#666666',
            fontWeight: 'normal',
            fontSize: 13
          }
        },
        xAxis: [
          {
            type: 'category',
            data: this.xData,
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            axisLine: {
              show: false
            },
            show: false
          }
        ],
        series: [
          {
            name: '222',
            type: 'bar',
            barWidth: '10px',
            data: this.tionData,
            smooth: true,
            itemStyle: {
              normal: {
                barBorderRadius: [5, 5, 0, 0],
                label: {
                  show: true,
                  position: 'top',
                  rotate: '30',
                  color: '#999999',
                  formatter: '¥{c}'
                },
                color:  (params) => {
                  return this.tionData.length-1 === params.dataIndex ?  '#E8B003' : '#E1E1E1';
                }
              }
            }
          }
        ]
      })
    },
    // 請求後臺接口
    aaa(data) {
      if(data){
        this.noData = false
        // 當dom節點從無到有時放在this.$nextTick()裏渲染
        this.$nextTick(()=> {
          this.statistics()
        })
      } else {
        this.noData = true
        this.statistics()
      }
    }
  },
  mounted () {
    this.statistics()
  }
}
</script>

4.總結dom


1.在methods鉤子函數裏自定義一個statistics()去渲染echarts
2.在mounted鉤子函數裏執行this.statistics()
3.請求後臺接口時候若是echarts圖表所在的dom存在(this.noData = false)放在this.$nextTick(()=> {this.statistics()})裏執行,不然(this.noData = true)直接this.statistics()函數


Vue.nextTick()做用:在下次dom更新循環結束以後執行延遲迴調。在修改數據以後當即使用這個方法,得到更新後的dom
若是不使用this.$nextTick() 在切換tab的時候dom從無到有,該節點還沒加載,不能獲取,會報錯
圖片描述
相關文章
相關標籤/搜索