全局引入
- 通過npm獲取echarts
npm install echarts --save - 在vue項(xiàng)目中引入echarts , 在 main.js 中添加下面兩行代碼
import * as echarts from 'echarts';
Vue.prototype.$echarts = echarts
注:import echarts from 'echarts' 引入echarts后,不能全局使用echarts,所以通過Vue.prototype將echarts保存為全局變量
- 頁面中是使用
//放圖表的容器 下面用ref獲取這個(gè)容器 所以要設(shè)置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)
}
這里要注意的是 我用的是彈框 所以獲取容器的時(shí)候報(bào)錯(cuò) 因?yàn)檫@個(gè)容器還沒繪制出來 所以在調(diào)用初始化之前加了延遲
setTimeout(() => {
this.drawChart();
}, 200)