全局引入
- 通过npm获取echarts
npm install echarts --save - 在vue项目中引入echarts , 在 main.js 中添加下面两行代码
import * as echarts from 'echarts';
Vue.prototype.$echarts = echarts
注:import echarts from 'echarts' 引入echarts后,不能全局使用echarts,所以通过Vue.prototype将echarts保存为全局变量
- 页面中是使用
//放图表的容器 下面用ref获取这个容器 所以要设置ref属性
<div id="main" style="width: 600px;height: 400px;" ref="myChart"></div>
drawChart() {
//初始化
const chartBox = this.$echarts.init(this.$refs.myChart);
const option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line'
}
]
};
chartBox.setOption(option)
}
这里要注意的是 我用的是弹框 所以获取容器的时候报错 因为这个容器还没绘制出来 所以在调用初始化之前加了延迟
setTimeout(() => {
this.drawChart();
}, 200)