一个基于 JavaScript 的开源可视化图表库
1.安装echarts
npm install echarts --save
2.在main.js中引入并全局挂载echarts
import { createApp } from 'vue'
import App from '@/App.vue'
//引入echarts
import * as echarts from 'echarts'
const app = createApp(App)
//全局挂载echarts
app.config.globalProperties.$echarts = echarts
3.在组件中使用echarts
注意代码中需要设置div宽/高的样式,否则图不会显示在页面上
<template>
<div>
<div id="barchar"></div>
<div id="linechar"></div>
</div>
</template>
<script>
export default {
data() {
return {};
},
methods: {
// 柱形图
change() {
//获取组件实例-- 基于准备好的dom,初始化echarts实例
const barBox = this.$echarts.init(document.getElementById("barchar"));
// 设置配置项
const option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [120, 200, 150, 80, 70, 110, 130],
type: 'bar',
showBackground: true,
backgroundStyle: {
color: 'rgba(180, 180, 180, 0.2)'
}
}
]
};
barBox.setOption(option);
// 根据页面大小自动响应图表大小
window.addEventListener("resize", function () {
barBox.resize();
});
},
// 折线图
changeLine() {
//获取组件实例-- 基于准备好的dom,初始化echarts实例
const lineBox = this.$echarts.init(document.getElementById("linechar"));
// 设置配置项
const option = {
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'
}
]
};
// 复制
lineBox.setOption(option);
// 根据页面大小自动响应图表大小
window.addEventListener("resize", function () {
lineBox.resize();
});
},
},
mounted() {
this.change();
this.changeLine();
},
};
</script>
<style lang="scss" scoped>
#barchar {
min-width: 30rem;
min-height: 30rem;
}
#linechar {
min-width: 30rem;
min-height: 30rem;
}
</style>