Vue+Echarts实现图表
一、Echarts的安装引入
1、在项目中安装echarts
cnpm install echarts --s
2、在需要图表的地方引入Eharts
(1)在需要图表的vue文件中引入(图表的引入)
<template>
<div id="main" style="width: 600px;height: 400px;"></div>
</template>
<script>
import echarts from 'echarts' //引入echarts
export default {
name: '',
data() {
.....
},
methods: {
drawLine(){
// 基于准备好的dom,初始化echarts实例
var myChart = this.echarts .init(document.getElementById(‘myChart‘)) //使用echarts组件
// 绘制图表
myChart.setOption({
title: { text: ‘在Vue中使用echarts‘ },
tooltip: {},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: ‘销量‘,
type: ‘bar‘,
data: [5, 20, 36, 10, 10, 20]
}]
});
}
}
}
</script>
(2)全局引入,在项目的 main.js 文件中引入,在需要图表的地方直接使用
main.js文件
import Vue from 'vue';
import './assets/fonts/iconfont.css';
import echarts from 'echarts'; //引入echarts
import App from './App.vue';
import router from './router';
Vue.prototype.$echarts = echarts //引入echarts组件
Vue.use(ElementUI);
Vue.config.productionTip = false;
new Vue({
router,
render: h => h(App)
}).$mount('#app')
index.vue(使用)
<div id="myChart" :style="{width: ‘300px‘, height: ‘300px‘}"></div>
<script>
export default {
name: ‘eCharts‘,
data () {
return {
msg: ‘Welcome to Your Vue.js App‘
}
},
mounted(){
this.drawLine();
},
methods: {
drawLine(){
// 基于准备好的dom,初始化echarts实例
var myChart = this.$echarts.init(document.getElementById(‘myChart‘)) //使用$echarts
// 绘制图表
myChart.setOption({
title: { text: ‘在Vue中使用echarts‘ },
tooltip: {},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: ‘销量‘,
type: ‘bar‘,
data: [5, 20, 36, 10, 10, 20]
}]
});
}
}
}
</script>
二、Vue+Echarts实现一个折线图
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 600px;height:400px;"></div>
<script>
export default {
name: ‘eCharts‘,
data () {
return {
msg: ‘Welcome to Your Vue.js App‘
}
},
mounted(){
this.drawLine();
},
methods: {
drawLine(){
// 基于准备好的dom,初始化echarts实例
var myChart = this.$echarts.init(document.getElementById(‘myChart‘)) //使用$echarts
// 绘制图表,指定图表配置项和数据
myChart.setOption({
title: { text: ‘销售增长量走势图‘ }, //title图表的标题
tooltip: {},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: ‘销量‘,
type: ‘bar‘, //line(折线图)、bar(柱状图)、pie(饼图)、scatter(散点图)、graph(关系图)、tree(树图)、...
data: [5, 20, 36, 10, 10, 20] //series的数据,对应着xAxis.data
}]
});
echartsOrder.setOption(option)
}
}
}
</script>
series指:一组数值以及他们映射成的图。
一个series至少包含一组数值(data)、图表类型(series.type)、以及其他的关于这些数据如何映射成图的参数。
echarts 里的(series.type)就是图表类型,series.type至少有:line(折线图)、bar(柱状图)、pie(饼图)、scatter(散点图)、graph(关系图)、tree(树图)、…
参考Echarts文档:文档连接