vue2使用echarts统计图完整代码
时间: 2023-09-15 17:15:19 浏览: 60
下面是一个简单的示例代码,展示了如何在 Vue2 中使用 Echarts 进行数据可视化:
1. 安装 Echarts
在 Vue2 项目中使用 Echarts,首先需要安装 Echarts。
可以通过 npm 安装:
```
npm install echarts --save
```
也可以通过 CDN 引入:
```html
<script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
```
2. 创建一个 Echarts 实例
在 Vue2 的组件中,可以使用 `mounted` 钩子函数创建一个 Echarts 实例,并渲染数据。
```vue
<template>
<div ref="chart" style="width: 600px; height: 400px;"></div>
</template>
<script>
import echarts from 'echarts';
export default {
mounted() {
const chart = echarts.init(this.$refs.chart);
// 在这里配置数据和图表样式
chart.setOption({
// Echarts 配置项
title: {
text: '某地区蒸发量和降水量',
subtext: '纯属虚构'
},
tooltip: {
trigger: 'axis'
},
legend: {
data: ['蒸发量', '降水量']
},
xAxis: {
type: 'category',
data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
},
yAxis: {
type: 'value'
},
series: [
{
name: '蒸发量',
type: 'bar',
data: [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
},
{
name: '降水量',
type: 'bar',
data: [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]
}
]
});
}
};
</script>
```
3. 渲染图表
在 `mounted` 钩子函数中,创建 Echarts 实例后,可以通过 `setOption` 方法配置 Echarts 图表的数据和样式。
最后,将 Echarts 实例渲染到页面上。在 Vue2 中,可以通过 `ref` 属性获取元素的引用,然后将引用传递给 Echarts 实例的 `init` 方法。
示例代码中,使用了一个 `div` 元素作为图表的容器,并给它设置了 `ref` 属性,以便在 Vue2 组件中获取它的引用。
```html
<template>
<div ref="chart" style="width: 600px; height: 400px;"></div>
</template>
```
在 `mounted` 钩子函数中,使用 `this.$refs.chart` 获取 `div` 元素的引用,并将它传递给 Echarts 实例的 `init` 方法。
```vue
mounted() {
const chart = echarts.init(this.$refs.chart);
// 在这里配置数据和图表样式
chart.setOption({
// Echarts 配置项
// ...
});
}
```
这样就可以在 Vue2 中使用 Echarts 进行数据可视化。