1、Vue.js中封装Echarts图表组件
封装Echarts子组件,父组件可以多次调用
<template>
<div :class="className" :id="id" :style="{height:height,width:width}"></div>
</template>
<script>
import echarts from 'echarts'
import resize from './mixins/resize'
export default {
mixins: [resize],
props: {
className: {
type: String,
default: 'chart'
},
id: {
type: String,
default: 'chart'
},
width: {
type: String,
default: '100%'
},
height: {
type: String,
default: '200px'
},
chartData: {
type: Object
}
},
data() {
return {
chart: null
}
},
mounted() {
this.initChart()
},
beforeDestroy() {
if (!this.chart) {
return
}
this.chart.dispose()
this.chart = null
},
watch: {
chartData: {
immediate: true,
deep: true,
handler(newVal, oldVal) {
if (this.chart) {
if (newVal) {
this.setOption(newVal)
} else {
this.setOption(oldVal)
}
}
}
}
},
methods: {
initChart() {
this.chart = echarts.init(document.getElementById(this.id), 'macarons')
this.setOption(this.chartData)
},
setOption(option) {
this.chart.setOption({
xAxis: {
data: this.chartData.xAxis.data,
axisTick: {
show: false
}
},
grid: {
left: 10,
right: 10,
bottom: 20,
top: 30,
containLabel: true
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross'