1.vue+swiper+echarts 循环轮播时第一个图表有时不显示
原因:swiper的loop设置为true了,会在原本slide前后复制若干个slide(默认一个)并在合适的时候切换,让Swiper看起来是循环的。所以复制出来的slide导致原本设置的echarts的id不在是唯一的。
使用echarts的图表是被封装过的组件,处理起来比较麻烦。
HTML部分:
<div class="flex-1 px-2" @mouseenter="stopSwiper('mySwiper')" @mouseleave="startSwiper('mySwiper')">
<swiper :options="swiperOption" class="w-100 h-100" ref="mySwiper" v-if="chartDataList.length">
<swiper-slide class="scroll-content" v-for="item in chartDataList" :key="item.targetChineseName">
<bar-and-line-chart-Indicator :ref="barAndLineChart" class="swiper-no-swiping barAndLineCharts my-border pb-3" :isAllShow="0" :chartData="item.chartData" ></bar-and-line-chart-Indicator>
</swiper-slide>
<div class="swiper-pagination" slot="pagination"></div>
</swiper>
</div>
js部分 :
复制得来的echarts(第一个和最后一个, 使用其所复制的那个echarts来执行其setOption方法。非复制的echarts,直接用其自身来调用setOption方法。
<script>
watch: {
// 需要渲染的图表的数据
chartDataList (val) {
if (val) {
if (val.length <= 1) { // 只有一条数据的时候不轮播
this.swiperOption.loop = false
this.swiperOption.autoplay = false
this.swiperOption.pagination = {
el: ''
}
} else {
this.swiperOption.loop = true
this.swiperOption.autoplay = true
this.swiperOption.pagination = {
el: '.swiper-pagination',
dynamicBullets: true,
dynamicMainBullets: 2,
type: 'bullets', // 分页器样式类型,默认bullets 圆点样式
clickable: true // 点击小圆点,也可以滚动轮播图。默认false
}
}
this.$nextTick(() => {
const chartClass = document.getElementsByClassName('barAndLineCharts')
for (let index = 0; index < chartClass.length; index++) {
// 不加的话轮播出来的还是有空的,可能是因为都渲染过了?
chartClass[index].setAttribute('_echarts_instance_', '')
// 复制得来的echarts(第一个和最后一个, 使用其所复制的那个echarts来执行其setOption方法。
let dom = null // 原因是我封装了折线柱状图,要使用$refs来调用子组件内部的option方法
if (index === 0) {
dom = this.$refs.barAndLineChart.slice(-1)[0]
} else if (index === chartClass.length - 1) {
dom = this.$refs.barAndLineChart[0]
} else {
// 非复制的echarts,直接用其自身来调用setOption方法。
dom = this.$refs.barAndLineChart[index - 1]
}
const myChart = echarts.init(chartClass[index])
if (dom) {
myChart.setOption(dom.option, true)
}
// 图表自适应
window.addEventListener('resize', function () {
myChart.resize()
})
}
})
}
}
},
</script>
2.如果swiper与含有dataZoom属性的echarts结合,想鼠标滑动平移图表的内容,会直接切换slide,而且图表的图例点击无反应,需要禁止swiper在图表中滑动,并且禁止之后发现图例点击后有反应。
将swiper的noSwiping属性设为true时,可以在slide上(或其他元素)增加类名 'swiper-no-swiping' ,使该slide无法拖动。该类名可通过 noSwipingClass 修改。
参考文章:
原文链接:https://blog.csdn.net/m0_37653407/article/details/112985595