Mosqkiller/src/views/counter/components/chart.vue

145 lines
3.0 KiB
Vue

<template>
<div id="chart" :class="className" :style="{height:height,width:width}"></div>
</template>
<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'
export default {
props: {
className: {
type: String,
default: 'chart'
},
width: {
type: String,
default: '100%'
},
height: {
type: String,
default: '350px'
},
autoResize: {
type: Boolean,
default: true
},
chartData: {
type: Object
},
showChart: {
type: Boolean
}
},
data() {
return {
chart: null
}
},
mounted() {
this.initChart()
if (this.autoResize) {
this.__resizeHanlder = debounce(() => {
if (this.chart) {
this.chart.resize()
}
}, 100)
window.addEventListener('resize', this.__resizeHanlder)
}
// 监听侧边栏的变化
const sidebarElm = document.getElementsByClassName('sidebar-container')[0]
sidebarElm.addEventListener('transitionend', this.__resizeHanlder)
},
beforeDestroy() {
if (!this.chart) {
return
}
if (this.autoResize) {
window.removeEventListener('resize', this.__resizeHanlder)
}
const sidebarElm = document.getElementsByClassName('sidebar-container')[0]
sidebarElm.removeEventListener('transitionend', this.__resizeHanlder)
this.chart.dispose()
this.chart = null
},
watch: {
chartData: {
deep: true,
handler(val) {
this.setOptions(val)
}
},
showChart(val) {
if (val) {
console.log(val)
this.chart.resize()
}
}
},
methods: {
setOptions({ historyData, xAxis, title } = {}) {
this.chart.setOption({
xAxis: {
// data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
data: xAxis,
boundaryGap: false,
axisLabel: {
interval: 0
},
axisTick: {
show: false
}
},
grid: {
left: 10,
right: 10,
bottom: 20,
top: 30,
containLabel: true
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross'
},
padding: [5, 10]
},
yAxis: {
axisTick: {
show: false
}
},
legend: {
data: [title]
},
series: [{
name: title, itemStyle: {
normal: {
color: '#FF005A',
lineStyle: {
color: '#FF005A',
width: 2
}
}
},
smooth: true,
type: 'line',
data: historyData,
animationDuration: 2800,
animationEasing: 'cubicInOut'
}]
})
},
initChart() {
this.chart = echarts.init(this.$el, 'macarons')
console.log(this.chartData)
// this.setOptions(this.chartData)
}
}
}
</script>