vue中引入echarts渲染问题

1.通过以下命令安装echarts

npm install echarts –save

2.在main.js文件里全局引入echarts

import echarts from ‘echarts’

Vue.prototype.$echarts = echarts

3.单页面引用echarts

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.总结

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从无到有,该节点还没加载,不能获取,会报错

《vue中引入echarts渲染问题》

    原文作者:何遇
    原文地址: https://segmentfault.com/a/1190000019508987
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞