Vue——整合EChart

Posted Starzkg

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue——整合EChart相关的知识,希望对你有一定的参考价值。

解决方案

<template>
  <div :style=" height: height, width: width " />
</template>

<script lang="ts">
import  defineComponent  from 'vue'

export default defineComponent(
  name: 'ECharts',
)
</script>

<script lang="ts" setup>
import * as echarts from 'echarts'
import 'echarts/theme/macarons'
import  debounce  from '@/utils/debounce'
import 
  nextTick,
  onMounted,
  onUnmounted,
  shallowRef,
  getCurrentInstance,
  watchEffect,
 from 'vue'
import  EChartsType  from 'echarts'

const instance = getCurrentInstance()

const props = defineProps(
  options: 
    type: Object,
    required: true,
  ,
  width: 
    type: String,
    default: '100%',
  ,
  height: 
    type: String,
    default: '100%',
  ,
)

const chart = shallowRef<EChartsType>()

const initChart = () => 
  if (instance) 
    chart.value = echarts.init(instance.proxy?.$el, 'macarons')
    chart.value?.setOption(props.options)
  


const resizeHandler = debounce(() => 
  if (chart.value) 
    chart.value.resize()
  
, 100)

onMounted(() => 
  nextTick(() => 
    initChart()
    window.addEventListener('resize', resizeHandler)
  )
)

onUnmounted(() => 
  if (!chart.value) 
    return
  
  window.removeEventListener('resize', resizeHandler)
  chart.value.dispose()
  chart.value = undefined
)

watchEffect(() => 
  if (chart.value) 
    chart.value.setOption(props.options)
  
)
</script>

<style lang="scss" scoped></style>


Demo

 <e-charts :options="options" height="300px" />

options 即 echarts 的options

参考文章

以上是关于Vue——整合EChart的主要内容,如果未能解决你的问题,请参考以下文章

Vue——整合EChart

Vue——整合EChart

vue 引入 echart

vue模块化(echart+element ui)

Vue项目优化,echart实例

Vue项目优化,echart实例