在 vue 3 中使用 echarts 需要执行以下步骤:安装 echarts:npm install --save echarts。导入 echarts:import * as echarts from 'echarts'。创建实例:在 mounted() 生命周期钩子中创建 echarts 实例并附加到 ref。配置选项:配置 echarts 选项,包括图表类型、数据和样式。销毁实例(可选):在 beforeunmount() 生命周期钩子中销毁 echarts 实例。
Vue 3 中使用 ECharts
如何使用 ECharts?
在 Vue 3 应用中使用 ECharts,需要执行以下步骤:
-
安装 ECharts:
立即学习“前端免费学习笔记(深入)”;
- npm install --save echarts
-
导入 ECharts:
- import * as echarts from 'echarts'
-
创建实例:
-
在 Vue 组件中,创建一个 ref 来引用 ECharts 实例:
- const chartRef = ref(null)
-
在 mounted() 生命周期钩子中创建一个 ECharts 实例并附加到 ref:
- mounted() { this.chartInstance = echarts.init(this.$refs.chartRef) }
-
-
配置选项:
-
配置 ECharts 选项,包括图表类型、数据和样式:
- `this.chartInstance.setOption({
...
})`
- `this.chartInstance.setOption({
-
-
销毁实例(可选):
-
在 beforeUnmount() 生命周期钩子中销毁 ECharts 实例:
- beforeUnmount() { if (this.chartInstance) this.chartInstance.dispose() }
-
示例:
<template><div ref="chartRef"></div>
</template><script>
import { ref, mounted, beforeUnmount } from 'vue'
import * as echarts from 'echarts'
export default {
setup() {
const chartRef = ref(null)
mounted() {
this.chartInstance = echarts.init(this.$refs.chartRef)
this.chartInstance.setOption({
title: { text: 'Vue 3 ECharts Example' },
series: [
{
type: 'pie',
data: [
{ value: 1, name: 'A' },
{ value: 2, name: 'B' },
{ value: 3, name: 'C' },
],
},
],
})
}
beforeUnmount() {
if (this.chartInstance) this.chartInstance.dispose()
}
},
}
</script>