//组件
<template>
<div ref="chartRef" class="echart"></div>
</template>
<script>
import * as echarts from 'echarts'
export default {
data() {
return {
chart: null
}
},
methods: {
init() {
if (!this.chart) {
this.chart = echarts.init(this.$refs.chartRef)
}
},
// 防抖
debounce(fun, delay) {
let timer
return function () {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
fun()
}, delay)
}
},
// 渲染图表
setOptions(option) {
if (!this.chart) return
this.chart.setOption(option)
},
// 图表重绘
setResize() {
if (!this.chart) return
this.chart.resize()
}
},
mounted() {
this.init()
window.addEventListener('resize', () => this.debounce(this.setResize(), 500))
},
beforeDestroy() {
if (!this.chart) return
this.chart = null
}
}
</script>
<style lang="scss" scoped>
.echart {
width: 100%;
height: 100%;
min-height: 200px;
}
</style>
使用
<template>
<div>
<VueChart ref="lineChartRef" />
</div>
</template>
<script>
import VueChart from './VueChart'
const lineOption = {
color: ['#317FF6', '#00FF7E'],
grid: {
top: '16%',
left: '2%',
right: '2%',
bottom: '2%',
containLabel: true
},
tooltip: {
trigger: 'axis'
},
legend: {
top: 10,
right: 10,
textStyle: { color: '#FFFFFF' }
},
xAxis: {
type: 'category',
axisLabel: {
color: '#C2D7E8',
fontSize: 12,
rotate: 45
},
axisLine: {
show: true,
lineStyle: { color: 'rgba(255, 255, 255, .2)' }
},
axisTick: { show: false },
data: ['星期一', '星期一', '星期一', '星期一', '星期一', '星期一', '星期一', '星期一', '星期一', '星期一', '星期一'],
},
yAxis: {
type: 'value',
name: '单位:家',
nameTextStyle: { color: '#C2D7E8' },
axisLabel: {
color: '#C2D7E8',
fontSize: 14
},
axisLine: {
show: true,
lineStyle: { color: 'rgba(255, 255, 255, .2)' }
},
splitLine: {
lineStyle: {
type: 'dashed',
color: 'rgba(255, 255, 255, .2)'
}
}
},
series: [
{
name: '总收入',
type: 'line',
smooth: true,
showSymbol: false,
areaStyle: {
// opacity: 0.8,
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(49, 127, 246, .5)'},
{ offset: 1, color: 'rgba(43, 254, 192, 0)' }
],
global: false
}
},
data: [20, 120, 110, 90, 50, 30, 35, 40, 50, 100, 90]
},
{
name: '纯收入',
type: 'line',
smooth: true,
showSymbol: false,
areaStyle: {
// opacity: 0.8,
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(43, 254, 192, .5)'},
{ offset: 1, color: 'rgba(43, 254, 192, 0)' }
],
global: false
}
},
data: [90, 50, 30, 35, 20, 120, 110, 90, 30, 35, 10]
}
]
}
export default {
name: 'Income',
components: {
VueChart
},
data() {
return {}
},
mounted() {
this.$refs.lineChartRef.setOptions(lineOption)
}
}
</script>