在 Vue 3.x + TypeScript(简称 Vue 3+TS)环境下使用 Echarts 需要注意一些细节,以下是具体的步骤:
1. 安装 ECharts
npm install echarts --save
2.在组件中声明 ECharts 变量
在 setup 函数中使用 ref 或 reactive 定义一个 ECharts 变量。ref 表示单个变量,reactive 表示一个对象。
import { ref } from 'vue';
import * as echarts from 'echarts';
export default {
setup() {
const chartRef = ref(null) // 创建 ECharts 变量
...
},
}
3.初始化 ECharts 实例
在 onMounted 钩子函数中初始化 ECharts 实例,同时使用 chartRef.value 获取 DOM 元素。
onMounted(() => {
const chartDom = chartRef.value;
if (chartDom && echarts) {
// 初始化 ECharts 实例
const myChart = echarts.init(chartDom);
...
}
});
4. 设置配置项和数据
将选项配置和数据传递给 ECharts 实例进行绑定
// 构建options
const option = {...};
// 渲染图表
myChart.setOption(option);
5.关于类型声明
TypeScript 中,无论是 .vue 文件还是 .js 文件,都需要使用 .d.ts 文件来添加类型声明。ECharts 提供了官方的类型声明文件,只需要在项目中安装 @types/echarts 就可以使用。
npm install @types/echarts --save-dev