vue学习后实战确实收获很多,今天分享下echarts作图简单使用
最近学习VUE ,之前爬取了一个小说网站,正好这次练习爬虫,顺便爬了一个
基金网站的数据。然后做了一个折线图,效果如下,就是输入基金编码,在输入天数,就可以生成多个基金的最近一段时间的折线图。
下面是随便找的三个基金生成的折线图
首先安装图表依赖包:npm install echarts --save
接下来 就在main.js中引用
import ECharts from 'echarts'
Vue.prototype.echarts=ECharts;
Vue.use(ECharts);
页面代码展示,代码也比较长主要就是数据格式,这里做了处理,格式样式是这样的
series.push({data:y,type:'line',smooth:true,name:key})
data:数据[1,2,3,4,5,6]
name:折线图对应的名称
<template>
<!--图表内容区域,必须给 ECharts 容器本身指定高度。不然它会使用默认高度-->
<div class = "chart">
<div id = "echarts" style = "height: 17.5rem"></div>
</div>
</template>
<script>
import echarts from 'echarts/lib/echarts'
import 'zrender/lib/svg/svg'
import 'echarts/lib/chart/line'
import 'echarts/lib/chart/candlestick'
// import chartUtil from '../../utils/chartUtil'
import {fundDetailApi} from "../../utils/index";
export default {
name: 'quotation',
data () {
return {
chart: null,
chartValue:[]
}
},
mounted () {
//初始化 ECharts 实例,不能在created生命周期内初始化,因为那时候DOM还没有渲染,是找不到元素的
this.initChart()
},
beforeDestroy () {
//组件销毁前先销毁 ECharts 实例
if (!this.chart) { return }
this.chart.dispose()
this.chart = null
},
methods: {
initChart () {
// 基于准备好的dom,初始化echarts实例,移动端建议使用 svg模式
this.chart = echarts.init(document.getElementById('echarts'), 'light', {renderer: 'svg'})
// this.chart.setOption(chartUtil.lineOption())
this.chart.clear();
let data=['001630','001302','320007'];
fundDetailApi({fundCode:data,size:90}).then(res=>{
let series = [];
let x = [];
let name =[]
for(var key in res.data) {
var chartValue = res.data[key];
let y = [];
for (var i = 0; i < chartValue.length; i++) {
if(x.indexOf(chartValue[i].x) == -1){
x.push(chartValue[i].x)
}
y[i] = chartValue[i].total
}
name.push(key)
series.push({data:y,type:'line',smooth:true,name:key})
}
const optionData = {
// 动态类型切换,切换图表
magicType: {
type: ['line', 'bar', ]
},
legend:{
data:name//对应的是name
},
xAxis: {
type: 'category',
data: x,
},
yAxis: {
name: '金额',
type: 'value',
scale:true,/*按比例显示*/
},
series:series
};
this.chart.setOption(optionData);
})
//图标根据窗口大小自动缩放
// window.addEventListener("resize", this.chart.resize);
},
},
}
</script>
这样一个简单的基金折线图就完成了。