下载包
npm install echarts --save
在main.js,导入包
import ECharts from 'echarts'
Vue.use(ECharts);
创建组件
<template>
<div id="main1" style="width: 600px;height:400px;"></div>
</template>
<script>
import echarts from 'echarts'
export default {
name: "figure",
methods:{
drawPie(id){
this.charts = echarts.init(document.getElementById(id));
this.charts.setOption({
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data:['销量']
},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
});
}
},
mounted() {
this.$nextTick(function () {
this.drawPie('main1');
})
}
}
</script>
<style scoped>
</style>
创建路由
vue代码和html代码的区别
-
官方教程文档
https://www.echartsjs.com/zh/tutorial.html#5%20%E5%88%86%E9%92%9F%E4%B8%8A%E6%89%8B%20ECharts
-
官方柱状图html代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ECharts</title>
<!-- 引入 echarts.js -->
<script src="echarts.min.js"></script>
</head>
<body>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
// 指定图表的配置项和数据
var option = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data:['销量']
},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>
</body>
</html>
现在我们对比一下vue和普通html代码的pub区别
- 导包,加引用
- html
<script src="echarts.min.js"></script>
- vue下载对应包,并且在
mian.js
中引入,还需要在使用ECharts的组件中引入
npm install echarts --save
- 为ECharts准备一个具备大小(宽高)的Dom,这个都是一样的,上图也有就是
div
<div id="main1" style="width: 600px;height:400px;"></div>
- 基于准备好的dom,初始化echarts实例,这个就不同了
- html
var myChart = echarts.init(document.getElementById('main'));
- vue,vue中就需要使用钩子函数
mounted
,不懂百度
methods:{
drawPie(id){
this.charts = echarts.init(document.getElementById(id));
}
},
mounted() {
this.$nextTick(function () {
this.drawPie('main1');
})
}
- 上述这个代码真正初始化也就是一行,这里mounted方法调用了drawPie方法,drawPie方法里面有下列代码,传入的参数就是div的id,让显示的图形和div联系起来
this.charts = echarts.init(document.getElementById(id));
- 指定图表的配置项和数据
- html
//数据
var option = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data:['销量']
},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
- vue,其实这两个代码也是一样的,只不过vue合并了,html拆开了
this.charts.setOption({
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data:['销量']
},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
});