echarts
下载
pnpm add echarts
基础使用
为 ECharts 准备一个定义了宽高的 DOM
<div ref="echartsRef" class="w-600px h-400px"></div>
基于准备好的dom,初始化echarts实例
import * as echarts from 'echarts'
var myChart = echarts.init(echartsRef.value)
指定图表的配置项和数据
var option = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data: ['销量']
},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
},
yAxis: {},
series: [
{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}
]
}
使用刚指定的配置项和数据显示图表。
myChart.setOption(option)
完整代码
<script lang="ts" setup>
import * as echarts from 'echarts'
const echartsRef = ref(null)
function initEcharts() {
var myChart = echarts.init(echartsRef.value)
// 指定图表的配置项和数据
var option = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data: ['销量']
},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
},
yAxis: {},
series: [
{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}
]
}
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option)
}
onMounted(() => {
initEcharts()
})
</script>
<template>
<div ref="echartsRef" class="w-600px h-400px"></div>
</template>
响应容器大小的变化
window.addEventListener('resize', function () {
myChart.value?.resize()
})
Cannot read properties of undefined (reading ‘type’) 报错
myChart 不要使用 ref 等,使用 shallowRef
const myChart = shallowRef()
myChart.value = echarts.init(echartsRef.value)