uni-app做echart图表(APP端)

640 阅读1分钟

写这遍文章,是因为在开发过程中uni-app开发APP端的时候,APP端做echart的文档实在太少了,开发多少有些坑,会发现在开发中浏览器调试h5可以显示,在app打包后就显示不了图表,对于此等原因,我封装了一个组件,实用于vue2和vue3来开发uniapp的

去官方下载好echartjs文件,放在下图的文件中就可以

2.png

封装的baseEchart.vue文件

<template>
  <view>
    <view :prop="option" id="echartId" :change:prop="echarts.updateEcharts" :style="echartStyle"></view>
  </view>
</template>

<script>
export default {
  props: {
    option: {},
    echartStyle: {
      default: {
        width: '100%',
        height: '600rpx'
      }
    }
  }
}
</script>

<script module="echarts" lang="renderjs">
	let myChart
	export default {
		mounted() {
			if (typeof window.echarts === 'function') {
				this.initEcharts()
			} else {
				const script = document.createElement('script')
				script.src = 'static/echarts.js'
				script.onload = this.initEcharts.bind(this)
				document.head.appendChild(script)
			}
		},
		methods: {
			initEcharts() {
				myChart = echarts.init(document.getElementById('echartId'))
			},
      updateEcharts(newValue) {
        setTimeout(() => {
          if (myChart) {
            myChart.setOption(newValue)
          }
        }, 200)
      }
		}
	}
</script>

引入上面的vue,直接使用就可以

传入的option就是echart的option,然后echartStyle就是echart的样式可以传

<baseEchart :option="option" />

有自己代码风格的可以忽略。这里多说一句,把option单独写成一个文件,option会经常变动,所以业务不是特别相似最好不要封装option,维护起来很累,然后暴露出去,代码逻辑就分离代码就很舒服,不要一堆option和业务揉在一起,看的想骂人,下面举个例子:

export const echartOption = (seriesData) => {
  // 可以处理后端返回的seriesData
  return {
      // 真正用用到的option对象
  }  
}