准备工作
安装echarts
npm install echarts -S
全局引用
首先在main.js中引入echarts,将其绑定到vue原型上:
import echarts from 'echarts'
Vue.prototype.$echarts = echarts;
然后我们就可以在任何一个组件中使用echarts了!
接下来我们以封装一个echarts组件为例:
<template>
<div>
<div ref="chart"></div>
</div>
</template>
<script>
export default{
data () {
return {};
},
methods: {
initCharts () {
let myChart = this.$echarts.init(this.$refs.chart);
// 绘制图表
myChart.setOption({
title: { text: '在Vue中使用echarts' },
tooltip: {},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
});
}
},
mounted () {
this.initCharts();
}
}
</script>
局部引用
局部引用代码会更加简洁,只在单个组件内使用即可:
<template>
<div>
<div ref="chart"></div>
</div>
</template>
<script>
const echarts = require('echarts');
export default{
data () {
return {};
},
methods: {
initCharts () {
let myChart = echarts.init(this.$refs.chart);
// 绘制图表
myChart.setOption({
title: { text: '在Vue中使用echarts' },
tooltip: {},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
});
}
},
mounted () {
this.initCharts();
}
}
</script>