如何在 Vue3 项目中使用 echarts
- 安装
- 在 vue 中引入
- 使用
- 例子
1. 安装
npm install echarts --save
2. 在 vue 中引入
import * as echarts from "echarts";
3.使用
-
引入 echarts
import * as echarts from "echarts" -
准备一个容器存放 echarts
-
挂载时初始化图表,卸载时销毁图表
-
基于准备好的 dom,初始化 echarts
-
配置 echarts
- 设置图表标题:title
- 设置直角坐标系的x轴:xAxis
- 设置直角坐标系的y轴:yAxis
- 设置提示框组件:tooltip
- 设置图例为柱状图和填充内容数据
完整示例:
子组件:
<template>
<div class="echarts-box">
<div id="myEcharts" :style="{ width: this.width, height: this.height }"></div>
</div>
</template>
<script setup>
import * as echarts from "echarts"
import { onMounted, onUnmounted } from "vue"
defineProps({
width: {
type: String,
default: 0,
},
height: {
type: String,
default: 0,
},
})
let myEcharts = echarts
// 挂载时初始化图表
onMounted(() => {
initChart()
})
// 卸载时销毁图表
onUnmounted(() => {
myEcharts.dispose;
})
function initChart () {
// 基于准备好的 dom,初始化 echarts 实例
let chart = myEcharts.init(document.getElementById("myEcharts"), "purple-passion");
chart.setOption({
// 设置图表标题
title: {
// 文本
text: "2021年各月份销售量(单位:件)",
// 位置
left: "center",
},
// x轴
xAxis: {
// 类型为离散
type: "category",
// x轴数据
data: [
"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
]
},
// 提示框组件
tooltip: {
trigger: "axis"
},
// y轴
yAxis: {
type: "value"
},
series: [
{
data: [
606, 542, 985, 687, 501, 787, 339, 706, 383, 684, 669, 737
],
// 设置图标类型为折线图
type: "line",
// 平滑曲线
smooth: true,
// 在顶部显示数据
label: {
show: true,
position: "top",
formatter: "{c}"
}
}
]
})
// 大小自适应窗口大小变化
window.onresize = function () {
// 重置容器宽高
chart.resize()
}
}
</script>
父组件
<template>
<echarts :width="'900px'" :height="'600px'"></echarts>
</template>
<script>
import Echarts from "./components/echarts.vue";
export default {
name: "App",
components: {
Echarts
},
}
</script>
<style>
</style>
\