vue中使用echarts 写一个柱状图图
时间: 2024-05-05 15:16:53 浏览: 93
首先,需要安装 echarts:
```
npm install echarts --save
```
然后,在 Vue 组件中引入 echarts:
```javascript
import echarts from 'echarts';
```
接着,在组件的 `mounted` 钩子中初始化 echarts:
```javascript
mounted() {
const myChart = echarts.init(document.getElementById('myChart'));
// ...
}
```
然后,设置 echarts 的配置项和数据:
```javascript
mounted() {
const myChart = echarts.init(document.getElementById('myChart'));
const option = {
title: {
text: '柱状图示例'
},
tooltip: {},
xAxis: {
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20, 5]
}]
};
myChart.setOption(option);
}
```
最后,在模板中添加一个 `div` 元素,并设置其 `id` 为 `myChart`:
```html
<template>
<div id="myChart" style="width: 600px; height: 400px;"></div>
</template>
```
完整的代码如下:
```html
<template>
<div id="myChart" style="width: 600px; height: 400px;"></div>
</template>
<script>
import echarts from 'echarts';
export default {
mounted() {
const myChart = echarts.init(document.getElementById('myChart'));
const option = {
title: {
text: '柱状图示例'
},
tooltip: {},
xAxis: {
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20, 5]
}]
};
myChart.setOption(option);
}
}
</script>
<style>
/* 样式可选 */
</style>
```
阅读全文