首先安装 npm install echarts --save (推荐使用cnpm,速度更快)
然后首先需要全局引入
在main.js中
import echarts from 'echarts'
Vue.prototype.$echarts = echarts
然后在vue组件中:
页面(html)
页面(script)
export default {
name: "index",
data(){
return {
chart: null, //关键一
myPie: null,
}
}
mounted(){
this.initCharts();
this.initCharts2();
this.init();
},
methods:{
initCharts () {
this.chart= this.$echarts.init(this.$refs.chart);
console.log(this.$refs.chart);
// 绘制图表
this.chart.setOption({
title: { text: '在Vue中使用echarts' },
tooltip: {},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
});
},
initCharts2 () {
this.myPie = this.$echarts.init(this.$refs.myPie);
console.log(this.$refs.myPie);
// 绘制图表
this.myPie.setOption({
title: { text: '在Vue中使用echarts' },
tooltip: {},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [25, 23, 66, 10, 10, 20]
}]
});
},
init() { //关键三 init的时候使用定时器监听窗口的变化,再调用echarts的resize方法
setTimeout(() => {
window.addEventListener('resize', () => {
this.chart.resize();
this.myPie.resize();
})
}, 20)
},
destroyed() { //关键四 定时清除init带来的定时器
window.removeEventListener('resize', this.init, 20)
},
}
}