一、安装echarts依赖
npm install echarts -S
二、引入echarts
(1)全局引入
main.js
import echarts from "echarts";
然后更改原型链,这样就可以在全局使用通过this.$echarts来全局使用了
Vue.prototype.$echarts = echarts;
使用图表
新建一个组件element.vue组件
<template>
<!--为echarts准备一个具备大小的容器dom-->
<div id="main" style="width: 600px;height: 400px;"></div>
</template>
<script>
//import echarts from 'echarts'
export default {
name: '',
data () {
return {
charts: '',
opinion:['直接访问','邮件营销','联盟广告','视频广告','搜索引擎'],
opinionData:[
{value:335, name:'直接访问'},
{value:310, name:'邮件营销'},
{value:234, name:'联盟广告'},
{value:135, name:'视频广告'},
{value:1548, name:'搜索引擎'}
]
}
},
methods:{
drawPie(id){
this.charts = this.$echarts.init(document.getElementById(id));//$echarts就是引入时原型链的更改
this.charts.setOption({
tooltip: {
trigger: 'item',
formatter: '{a}<br/>{b}:{c} ({d}%)'
},
legend: {
orient: 'vertical',
x: 'left',
data:this.opinion
},
series: [
{
name:'访问来源',
type:'pie',
radius:['50%','70%'],
avoidLabelOverlap: false,
label: {
normal: {
show: false,
position: 'center'
},
emphasis: {
show: true,
textStyle: {
fontSize: '30',
fontWeight: 'blod'
}
}
},
labelLine: {
normal: {
show: false
}
},
data:this.opinionData
}
]
})
}
},
//调用
mounted(){
this.$nextTick(function() {
this.drawPie('main')
})
}
}
</script>
<style scoped>
* {
margin: 0;
padding: 0;
list-style: none;
}
</style>
(二)按需引入
这时就不需要再main.js中进行配置了
再组件中引入自己需要的模板,更多模板https://github.com/ecomfe/echarts/blob/master/index.js
<script>
// 引入基本模板
// let echarts = require(‘echarts/lib/echarts‘)
var echarts = require(‘echarts‘)
// 引入柱状图组件
require(‘echarts/lib/chart/bar‘)
// 引入提示框和title组件
require(‘echarts/lib/component/tooltip‘)
require(‘echarts/lib/component/title‘)
export default {
name: ‘eCharts‘,
data () {
return {
msg: ‘Welcome to Your Vue.js App‘
}
},
mounted(){
this.drawLine();
},
methods: {
drawLine(){
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(this.$el);//console.log(this.$el)
// 绘制图表
myChart.setOption({
title: { text: ‘在Vue中使用echarts‘ },
tooltip: {},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: ‘销量‘,
type: ‘bar‘,
data: [5, 20, 36, 10, 10, 20]
}]
});
}
}
}
</script>
注:这里用 requir 不用 import 引入是因为 import 需要详细的路径
另外
var myChart = echarts.init(this.$el);//this.$el指的是当前组件的元素
按需引用的时候将 this.$echarts 改为 echarts(引入时的名)
三、echarts图表自适应
mounted() {
let vueThis = this;
window.addEventListener("resize",function (event) {
vueThis.chart.resize();
})
}