前言
本期主要讲解Vue3如何引入并且使用Echarts,那么好,本文正式开始。
第一步 下载
下载Echart这里我用的是npm install echarts --save
第二步 导入Echarts
新建图表组件BarEcharts,在script ts中,导入Echarts,同时导入onMounted, onUnmounted
import { onMounted, onUnmounted } from 'vue'
import * as Echarts from 'echarts'
创建动态数据props,起始我们先把宽高变成动态的。
props:["width","height"],
然后我们使用onMounted和onUnmounted,前者生成表格,后者销毁表。
onMounted(()=>{
initChart();
})
onUnmounted(()=>{
Echarts.dispose;
})
创建生成表相关函数与数据
function initChart(){
let chart = Echarts.init(document.getElementById("myCharts"), "purple-passion");
chart.setOption({
title: {
text: "2021年各月份销售量(单位:件)",
left: "center",
},
xAxis: {
type: "category",
data: [
"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"
]
},
tooltip: {
trigger: "axis"
},
yAxis: {
type: "value"
},
series: [
{
data: [
606, 542, 985, 687, 501, 787, 339, 706, 383, 684, 669, 737
],
type: "bar",
smooth: true,
itemStyle: {
normal: {
label: {
show: true,
position: "top",
formatter: "{c}"
}
}
}
}
]
});
window.onresize = function () {
chart.resize();
};
}
最后return {initChart}
templalte模板:
<div id="myCharts" :style="{width:width,height:height}"></div>
导入组件
<BarEcharts :width="'900px'" :height="'500px'"/>