以简单的折线图为例
下载echarts:npm install echarts --save
根据ref获取dom用法:
<template>
<div>
<div id="chart" ref="chartRef"></div>
</div>
</template>
<script setup lang="ts">
import { onMounted, ref, type Ref } from 'vue';
import * as echarts from 'echarts';
type EChartsOption = echarts.EChartsOption
const chartRef: Ref<HTMLElement | null> = ref(null);
let chart: echarts.ECharts
onMounted(() => {
chart = echarts.init(chartRef.value as HTMLElement);
updateChart();
})
const updateChart = () => {
const option: EChartsOption = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line'
}
]
};
option && chart.setOption(option);
}
</script>
<style scoped>
#chart {
width: 600px;
height: 400px;
}
</style>
原始方法获取dom用法
<template>
<div>
<div id="chart" ref="chartRef"></div>
</div>
</template>
<script setup lang="ts">
import { onMounted } from 'vue';
import * as echarts from 'echarts';
type EChartsOption = echarts.EChartsOption
onMounted(() => {
chartFn();
})
const chartFn = () => {
// 获取dom,断言HTMLElement类型,否则会报错
const chartEle: HTMLElement = document.getElementById('chart') as HTMLElement;
const chart = echarts.init(chartEle);
const option: EChartsOption = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line'
}
]
};
option && chart.setOption(option);
}
</script>
<style scoped>
#chart {
width: 600px;
height: 400px;
}
</style>