需求:首页显示多种类型的统计图(封装多个组件方便后续使用)
问题:数据获取后无法渲染到界面( vue axios属于异步加载数据)
解决:利用watch,监控数据变化,根据变化调用渲染echarts的方法
参考:
- 按需引入:https://echarts.apache.org/examples/zh/index.html
一、创建组件(components/charts/lineArea.vue)
// echarts按需引入
<template>
<div ref="dom"></div>
</template>
<script>
const echarts = require('echarts/lib/echarts');
require('echarts/lib/component/grid');
require('echarts/lib/chart/line');
import { on, off } from '@/utils/onOff.js' //这个是封装的功能
export default {
name: 'LineArea',
props: {
xValue: Array,
yValue:Array,
},
data () {
return {
dom: null
}
},
watch:{ //使用watch监控数据变化然后去调用echartsShow渲染echarts
xValue(newVal){
this.xValue = newVal
this.echartsShow()
},
yValue(newVal){
this.yValue = newVal
this.echartsShow()
}
},
methods: {
resize () {
this.dom.resize()
},
echartsShow(){
this.$nextTick(() => {
let xData = this.xValue
let yData = this.yValue;
console.log('数据x',xData);
console.log('数据y',yData);
const option = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
label: {
backgroundColor: '#2F54EB'
}
}
},
grid: {
top: '3%',
left: '24px',
right: '24px',
bottom: '3%',
containLabel: true
},
xAxis: [
{
type: 'category',
boundaryGap: false,
data: xData
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
name: '运营商/网络服务',
type: 'line',
showSymbol: false,
stack: '总量',
areaStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
offset: 1,
color: 'rgba(255, 255, 255, 0.8)'
}, {
offset: 0,
color: 'rgba(47, 84, 235, 0.3)'
}])
},
data: yData
}
]
}
this.dom = echarts.init(this.$refs.dom)
this.dom.setOption(option)
on(window, 'resize', this.resize)
})
}
},
beforeDestroy () {
off(window, 'resize', this.resize)
}
}
</script>
- 工具(util/onOff.js)
/**
* @description 解绑事件 off(element, event, handler)
*/
export const off = (function () {
if (document.removeEventListener) {
return function (element, event, handler) {
if (element && event) {
element.removeEventListener(event, handler, false)
}
}
} else {
return function (element, event, handler) {
if (element && event) {
element.detachEvent('on' + event, handler)
}
}
}
})()
/**
* @description 绑定事件 on(element, event, handler)
*/
export const on = (function () {
if (document.addEventListener) {
return function (element, event, handler) {
if (element && event && handler) {
element.addEventListener(event, handler, false)
}
}
} else {
return function (element, event, handler) {
if (element && event && handler) {
element.attachEvent('on' + event, handler)
}
}
}
})()
二、引入组件(page/index/index.vue)
<template>
<div>
//引入组件
<line-area :xValue='xData' :yValue='yData'></line-area>
</div
</template>
<script>
import { getData} from '@/services/api.js'
import lineArea from '@/components/charts/lineArea.vue'
export default{
componts:{
lineArea,
},
data(){
return {
xData:[],
yData:[]
}
},
methods:{
//接口请求获取数据
getData({}).then((res)=>{
this.nextTick(()=>{
res.forEach((item) => {
this.yData.push(item.y)
this.xData.push(item.x)
})
})
})
}
}
</script>
参数资料:https://github.com/iview/iview-admin