1、用vite创建好一个ts项目
2、下载echarts
npm install echarts --save pnpm add echarts
复制
3、引入echarts(建议不要全局引入,按需引入不然暂用过大)
// 按需引入echarts图(这里引入的是折线图) import * as echarts from 'echarts/core'; import { GridComponent, GridComponentOption } from 'echarts/components'; import { LineChart, LineSeriesOption } from 'echarts/charts'; import { UniversalTransition } from 'echarts/features'; import { CanvasRenderer } from 'echarts/renderers'; echarts.use([GridComponent, LineChart, CanvasRenderer, UniversalTransition]); type EChartsOption = echarts.ComposeOption< GridComponentOption | LineSeriesOption >;
复制
4、父组件(更多options设置查看Apache ECharts)
//App.vue <template> <Charts :option="option" chartHeight="400px"></Charts> </template> <script lang='ts' setup> import { ref } from 'vue' // 引入echarts组件 import Charts from './charts/charts.vue'; //引入echarts代码在(3)中 const option = ref<EChartsOption>({ xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [ { data: [820, 932, 901, 934, 1290, 1330, 1320], type: 'line', smooth: true } ] }) </script>
复制
5、子组件(charts.vue)
<!----> <template> <div :style="{ height: chartHeight, width: '100%' }" ref="chart"></div> </template> <script lang='ts' setup> import { ref, onMounted, onBeforeUnmount, markRaw } from 'vue' import * as echarts from 'echarts/core' const chart = ref<HTMLDivElement>() const myChart = ref() // 接受父组件传过来的option,和echarts的高度 // 可以根据父组件传过来的option对象生成折线图、柱状图、饼图等等。 const props = defineProps(['option', 'chartHeight']) onMounted(() => { // 函数体 // console.log(props.option); // !!!这里必须用markRaw包裹住,否则当页面宽度变化控制台会报错 myChart.value = markRaw(echarts.init(chart.value as HTMLDivElement)) myChart.value.setOption(props.option) // 监听页面视图变化echarts图的宽度变化 window.addEventListener("resize", () => { myChart.value.resize() }) }) // 组件销毁前一定要取消监听的事情,不然会印象性能和暂用内存 onBeforeUnmount(() => { window.removeEventListener("resize", () => { myChart.value.resize() }) }) </script> <style scoped></style>
复制
6、运行结果