echarts之响应式的实现
BarChart.vue
<template>
<div ref="chartP" class="bar-chart-wrap">
<div :id="id" class="chart"></div>
</div>
</template>
<script>
export default {
name: "BarChart",
props: {
id: {
type: String,
default: "barChart",
},
seriesData: {
type: Object,
default: () => {},
},
},
computed: {
echarts() {
return "echarts" + Math.random() * 100000;
},
},
watch: {
seriesData: {
handler: function (newV) {
console.log("newV", newV);
this.drawBar();
},
deep: true,
},
},
data() {
return {
myChart: null,
};
},
mounted() {
this.$nextTick(() => {
this.drawBar();
});
},
activated() {
if (this.myChart) {
setTimeout(() => {
this.myChart.resize();
}, 200);
}
},
methods: {
drawBar() {
this.myChart = this.$echarts.init(document.getElementById(this.id));
this.myChart.setOption({
color: ["#133891"],
grid: {
left: "0%",
right: "0%",
bottom: "0%",
},
xAxis: {
type: "category",
data: this.seriesData.xAxis,
splitLine: { show: false },
axisTick: { show: false },
axisLine: {
show: false,
},
},
yAxis: {
type: "value",
show: false,
},
series: [
{
data: this.seriesData.series,
type: "bar",
barWidth: "30%",
barGap: "70%",
label: {
show: true,
position: "top",
},
},
],
});
},
},
};
</script>
<style scoped lang="scss">
.bar-chart-wrap {
width: 100%;
height: 100%;
position: relative;
.chart {
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
width: 100%;
height: 100%;
}
}
</style>
使用组件
<template>
<div class="user2">
<div class="user2-echrts">
<div class="chart" v-for="(item, index) of sinosureList" :key="index">
<div class="bar-chart">
<barchart :id="`barchart${index + 1}`" :seriesData="item"></barchart>
</div>
</div>
</div>
</div>
</template>
<script>
import barchart from "./childCom/echarts/barChart.vue";
export default {
name: "User2",
components: {
barchart,
},
data() {
return {
sinosureList: [
{
series: [38.06, 66.6],
xAxis: ["2020", "2021"],
},
{
series: [48.06, 26.6],
xAxis: ["2020", "2021"],
},
{
series: [58.06, 76.6],
xAxis: ["2020", "2021"],
},
],
};
},
activated() {
window.addEventListener("resize", this.resizeHandler, false);
},
deactivated() {
window.removeEventListener("resize", this.resizeHandler);
},
methods: {
// 这是再当前页面拉动 页面的时候 实现echart是响应式
resizeHandler() {
const barchart1 = this.$echarts.init(
document.getElementById("barchart1")
);
const barchart2 = this.$echarts.init(
document.getElementById("barchart2")
);
const barchart3 = this.$echarts.init(
document.getElementById("barchart3")
);
barchart1 && barchart1.resize();
barchart2 && barchart2.resize();
barchart2 && barchart3.resize();
},
},
};
</script>
<style lang="scss" scoped>
.echrts2 {
margin-top: 1000px;
}
.user2 {
height: 100%;
width: 100%;
.user2-echrts {
display: flex;
position: relative;
height: 300px;
width: 100%;
background:
.chart {
width: 33.333%;
height: 60%;
display: flex;
align-items: flex-end;
}
.bar-chart {
width: 40%;
height: 100%;
margin-left: 32%;
}
}
}
</style>