npm install echarts --save
接下来 compoents 中封装公共组件
子组件
<!--Echarts组件-->
<template>
<div ref="main" class="main" :style="{ width: width, height: height }" />
</template>
<script lang="ts" setup>
import { ref, defineProps, watch, onMounted, onBeforeUnmount, withDefaults } from 'vue'
import * as echarts from 'echarts'
import { ECBasicOption, EChartsType } from 'echarts/types/dist/shared'
import { EventParams } from '@/utils/echarts.ts'
interface EchartsProps {
options: ECBasicOption | null
width?: string
height?: string
handlerClick?: (params: EventParams) => void | null
}
let instance: EChartsType = null as unknown as EChartsType
//withDefaults可以设置默认值 这里我们需要初始化就设置子组件的默认宽度高度
const props = withDefaults(defineProps<EchartsProps>(), {
width: '100%',
height: '100%'
})
const main = ref(null)
// 初始化图表
const initEcharts = () => {
if (props.options == null) return
// as unknown as HTMLElement 定义的是document.getElementById 类似于这种方式拿值 的 数据类型
instance = echarts.init(main.value as unknown as HTMLElement) as unknown as EChartsType
instance.setOption(props.options as ECBasicOption)
instance.on('click', handlerClick)
window.onresize = handlerSize
}
function handlerSize() {
instance.resize()
}
function handlerClick(params: EventParams | any): void {
if (props.handlerClick != null) {
props.handlerClick(params)
}
}
onMounted(() => {
initEcharts()
})
onBeforeUnmount(() => {
if (instance) {
instance.dispose()
window.removeEventListener('onresize', handlerSize)
}
})
watch(props, () => {
if (instance) {
instance.setOption(props.options as ECBasicOption)
} else {
initEcharts()
}
})
</script>
<style scoped lang="scss">
.main {
width: 100%;
height: 100%;
}
</style>
使用的时候:(父组件)
<!-- 组件用途 ts基础模板 -->
<template>
<div>首页</div>
<Echarts :options="options" :width="'200px'" :height="'200px'" />
</template>
<script lang="ts" setup>
import Echarts from '@/components/echarts/Echarts.vue'
import { onMounted, ref } from 'vue'
let options = ref<any>(null)
onMounted(() => {
options.value = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data: ['数量']
},
xAxis: {
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {},
series: [
{
name: '数量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}
]
}
})
</script>
<style lang="scss" scoped></style>
utils文件夹下建 echarts.ts文件定义类型
export type EventParams = {
// 当前点击的图形元素所属的组件名称,
// 其值如 'series'、'markLine'、'markPoint'、'timeLine' 等。
componentType: string
// 系列类型。值可能为:'line'、'bar'、'pie' 等。当 componentType 为 'series' 时有意义。
seriesType: string
// 系列在传入的 option.series 中的 index。当 componentType 为 'series' 时有意义。
seriesIndex: number
// 系列名称。当 componentType 为 'series' 时有意义。
seriesName: string
// 数据名,类目名
name: string
// 数据在传入的 data 数组中的 index
dataIndex: number
// 传入的原始数据项
data: Object
dataType: string
// 传入的数据值
value: number | Array
// 数据图形的颜色。当 componentType 为 'series' 时有意义。
color: string
}