现实的工做中, 数据不多是像以前的demo演示的那样把数据写死的. 全部的数据都应该经过发送请求进行获取, 因此, 这篇文章, 我将在Vue项目中使用Echarts: 在Vue中引入Echarts中的数据提取出来, 放入到static/data.json
文件中,请求该文件获取数据。vue
//命令行中输入
npm install axios --saveios
// main.js
import http from './http'
Vue.prototype.$http = http //挂载到原型上npm
将该柱状图的没有数据的option抽取到data.json中, 代码以下:json
{ "title": { "text": "简单饼状图" }, "tooltip": {}, "xAxis": { "data": ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"], "name": "产品" }, "yAxis": {}, "series": [{ "name": "销量", "type": "bar", "data": [5, 20, 36, 10, 10, 20], "itemStyle": { "normal": { "color": "hotpink" } } }] }
代码以下:axios
<template> <div id="myChart" :style="{width: '800px', height: '400px'}"></div> </template> <script> export default { name: 'echarts', data() { return { msg: 'Welcome to Your Vue.js App', goods: {} } }, mounted() { this.drawLine(); }, created() { this.$http.get('./static/dat.json').then(res => { const data = res.data; this.goods = data console.log(this.goods); console.log(Array.from(this.goods.xAxis.data)); }) }, methods: { drawLine() { // 基于准备好的dom,初始化echarts实例 let myChart = this.$echarts.init(document.getElementById('myChart')) // 绘制图表 myChart.setOption({ title: {}, //{text: '异步数据加载示例'}, tooltip: {}, xAxis: { data: [] //["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"] }, yAxis: {}, series: [{ name: '销量', type: 'bar', data: [] //[5, 20, 36, 10, 10, 20] }] }); this.$http.get("./static/dat.json") .then((res) => { const data = res.data; const list = data.series.map(good=>{ let list = good.data; return [...list] }) console.log(list); console.log(Array.from(...list)); myChart.setOption({ title: data.title, xAxis: [{ data: data.xAxis.data }], series: [{ name: '销量', type: 'bar', data: Array.from(...list) //[5, 20, 36, 10, 10, 20] }] }); }) } } } </script>
若是数据加载时间较长,一个空的坐标轴放在画布上也会让用户以为是否是产生 bug 了,所以须要一个 loading 的动画来提示用户数据正在加载。echarts
ECharts 默认有提供了一个简单的加载动画。只须要调用 showLoading 方法显示。数据加载完成后再调用 hideLoading 方法隐藏加载动画。dom
在drawLine()
方法中添加showLoading()
和hideLoading()
, 代码以下:异步
methods: { drawLine() { // 基于准备好的dom,初始化echarts实例 let myChart = this.$echarts.init(document.getElementById('myChart')) // 绘制图表 myChart.setOption({ title: {}, //{text: '异步数据加载示例'}, tooltip: {}, xAxis: { data: [] //["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"] }, yAxis: {}, series: [{ name: '销量', type: 'bar', data: [] //[5, 20, 36, 10, 10, 20] }] }); //显示加载动画 myChart.showLoading(); this.$http.get("./static/dat.json").then((res) => { setTimeout(() => { //将来让加载动画效果明显,这里加入了setTimeout,实现3s延时 const data = res.data; const list = data.series.map(good => { let list = good.data; return [...list] }) console.log(list); console.log(Array.from(...list)); myChart.hideLoading(); //隐藏加载动画 myChart.setOption({ title: data.title, xAxis: [{ data: data.xAxis.data }], series: [{ name: '销量', type: 'bar', data: Array.from(...list) //[5, 20, 36, 10, 10, 20] }] }); }, 3000) }) } }