vue之 echarts的响应式处理
chart
<template>
<div ref="chart" class="chart-box" :style="{height: height ,width: domWidth}" />
</template>
<script>
import echarts from 'echarts/lib/echarts'
export default {
name: 'LineChart',
props: {
chartData: {
type: Array,
default: () => { return [] }
},
optionMethod: {
type: Function,
default: (para) => { return {} }
},
height: {
type: String,
default: '400px'
},
width: {
type: String,
default: '100%'
}
},
data() {
return {
chart: null
}
},
computed: {
domWidth() {
return this.width
}
},
watch: {
chartData(val) {
const iVal = this.$_.cloneDeep(val)
const option = this.optionMethod(iVal)
this.setOption(option)
}
},
mounted() {
this.initChart()
const option = this.optionMethod(this.chartData)
this.setOption(option)
},
methods: {
initChart() {
this.chart = echarts.init(this.$refs['chart'])
window.addEventListener('resize', () => { this.chart.resize() })
},
setOption(option) {
this.chart.clear()
this.chart.setOption(option)
}
}
}
</script>
使用 echart
<div ref="domF" class="domF">
<LineChart
id="domID"
:chart-data="chartData"
:option-method="chartConfig.opMethod"
:height="chartHeight"
:width="chartWidth"
/>
</div>
import echarts from 'echarts/lib/echarts'
data数据
chartHeight: '400px',
chartWidth: '100%'
watch: {
chartWidth(newV) {
if (newV === '0px' || newV === 'undefinedpx') return false
const barchart3 = echarts.init(
document.getElementById('domID')
)
barchart3 && barchart3.resize()
}
},
mounted() {
window.onresize = () => {
this.resizeHandler()
}
},
resizeHandler() {
const chartWidth = this.$refs?.domF?.offsetWidth + 'px'
this.chartWidth = chartWidth === '0px' ? '100%' : chartWidth
}
async initData(timeFrom, timeTill) {
this.chartData = data.data.results
this.resizeHandler()
},