解决方案
<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
参考文章
|