EcChart.vue 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <template>
  2. <!-- 微信小程序使用 ec-canvas -->
  3. <view v-if="isMp" class="chart-wrapper">
  4. <uni-ec-canvas id="line-chart" :style="{ width, height }" canvas-id="multi-charts-line" :ec="ec" ref="canvas" />
  5. </view>
  6. <!-- H5 / App 使用普通 div 方式挂载 echarts -->
  7. <div v-else ref="canvasDom" class="chart-wrapper" :style="{ width, height }" />
  8. </template>
  9. <script>
  10. import uniEcCanvas from '@/echarts/uni-ec-canvas/uni-ec-canvas.vue'
  11. export default {
  12. name: 'EcChart',
  13. components: {
  14. uniEcCanvas
  15. },
  16. props: {
  17. chartOption: Object,
  18. width: { type: String, default: '100%' },
  19. height: { type: String, default: '300px' }
  20. },
  21. data() {
  22. return {
  23. ec: {
  24. lazyLoad: true
  25. },
  26. isMp: false
  27. }
  28. },
  29. mounted() {
  30. this.isMp = process.env.UNI_PLATFORM === 'mp-weixin'
  31. this.$nextTick(() => {
  32. setTimeout(() => {
  33. if (this.isMp) {
  34. this.$refs.canvas.init(this.initChartMp)
  35. } else {
  36. this.initChartWeb()
  37. }
  38. }, 100)
  39. })
  40. },
  41. beforeDestroy() {
  42. // 只在非小程序端调用 dispose
  43. if (!this.isMp && this.chart && typeof this.chart.dispose === 'function') {
  44. this.chart.dispose()
  45. this.chart = null
  46. }
  47. },
  48. methods: {
  49. async initChartWeb() {
  50. const echarts = await import('echarts') // npm 安装的 echarts
  51. this.chart = echarts.init(this.$refs.canvasDom)
  52. this.chart.setOption(this.chartOption)
  53. window.addEventListener('resize', () => {
  54. this.chart && this.chart.resize()
  55. })
  56. },
  57. // 小程序端初始化 chart 实例
  58. initChartMp(canvas, width, height, dpr) {
  59. const echarts = require('@/echarts/uni-ec-canvas/echarts.min.js')
  60. const chart = echarts.init(canvas, null, {
  61. width,
  62. height,
  63. devicePixelRatio: dpr
  64. })
  65. canvas.setChart(chart)
  66. chart.setOption(this.chartOption)
  67. this.chart = chart
  68. return chart
  69. }
  70. }
  71. }
  72. </script>
  73. <style scoped>
  74. .chart-wrapper {
  75. width: 100%;
  76. height: 100%;
  77. }
  78. </style>