一、起因
本人负责的一个项目需要用到仪表盘和折线图,但是折线图是放在swiper中的,而折线图中数据非常多,需要touchmove事件查看后续数据,但是touchmove又会出现冒泡事件导致触发swiper的touchmove事件,详情可以看此处。但是禁止事件冒泡以后我发现我的仪表盘事件冒泡也被禁止了,导致无法屏幕下拉。
二、解决过程
一开始还是挺没有头绪的,我知道是因为我禁止了事件冒泡导致的后果,但是我的折线图又是需要禁止事件冒泡的,让我处于两难的境地,但是我看ucharts源码的时候发现用到了很多#ifdef和#endif,我就想是否可以根据不同的type来使用不同的h5,于是着手修改程序。
鉴于vue具有v-if这样方便的判断,只需要找到通过v-if判断的内容就行了。我需要根据我传入的type进行判断,于是在组件中我找到了props,内容如下
props: {
type: {
type: String,
default: null
},
canvasId: {
type: String,
default: 'uchartsid'
},
canvas2d: {
type: Boolean,
default: false
},
background: {
type: String,
default: 'rgba(0,0,0,0)'
},
animation: {
type: Boolean,
default: true
},
chartData: {
type: Object,
default() {
return {
categories: [],
series: []
};
}
可以看到第一个type就是我们要找的type了,于是直接在view中使用v-if=“type===’line‘”即可,由于我使用的是仪表盘和折线图,所以需要v-if和v-elseif v-else,我修改完的h5如下
<view v-if="type==='gauge'">
<scroll-view scroll-x="true" ><!-- v-on:touchmove.stop.prevent="rdcharts.touchMove" -->
<view
v-on:tap="rdcharts.tap"
v-on:mousemove="rdcharts.mouseMove"
v-on:mousedown="rdcharts.mouseDown"
v-on:mouseup="rdcharts.mouseUp"
v-on:touchstart="rdcharts.touchStart"
v-on:touchmove="rdcharts.touchMove"
v-on:touchend="rdcharts.touchEnd"
:id="'UC'+cid"
:prop="uchartsOpts"
:change:prop="rdcharts.ucinit"
>
<canvas
:id="cid"
:canvasId="cid"
:style="{ width: cWidth + 'px', height: cHeight + 'px', background: background }"
:disable-scroll="disableScroll"
@error="_error"
v-show="showchart"
/>
</view>
</scroll-view>
</view>
<view v-else-if="type==='line'">
<scroll-view scroll-x="true" v-on:touchmove.stop.prevent="rdcharts.touchMove"><!-- -->
<view
v-on:tap="rdcharts.tap"
v-on:mousemove="rdcharts.mouseMove"
v-on:mousedown="rdcharts.mouseDown"
v-on:mouseup="rdcharts.mouseUp"
v-on:touchstart="rdcharts.touchStart"
v-on:touchmove="rdcharts.touchMove"
v-on:touchend="rdcharts.touchEnd"
:id="'UC'+cid"
:prop="uchartsOpts"
:change:prop="rdcharts.ucinit"
>
<canvas
:id="cid"
:canvasId="cid"
:style="{ width: cWidth + 'px', height: cHeight + 'px', background: background }"
:disable-scroll="disableScroll"
@error="_error"
v-show="showchart"
/>
</view>
</scroll-view>
</view>
<view v-else>
<view
v-on:tap="rdcharts.tap"
v-on:mousemove="rdcharts.mouseMove"
v-on:mousedown="rdcharts.mouseDown"
v-on:mouseup="rdcharts.mouseUp"
v-on:touchstart="rdcharts.touchStart"
v-on:touchmove="rdcharts.touchMove"
v-on:touchend="rdcharts.touchEnd"
:id="'UC'+cid"
:prop="uchartsOpts"
:change:prop="rdcharts.ucinit"
>
<canvas
:id="cid"
:canvasId="cid"
:style="{ width: cWidth + 'px', height: cHeight + 'px', background: background }"
:disable-scroll="disableScroll"
@error="_error"
v-show="showchart"
/>
</view>
</view>
其中第一段view为仪表盘允许事件冒泡,第二段为折线图,不允许事件冒泡,第三段为原本的程序,代表其他类型的type使用的是默认的h5
三、 小结
通过v-if的办法可以有效的控制使用不同的h5界面,当然如果有更复杂的需求可以在js中使用computed之类的来进行运算和动态绑定。本文也只是给出了一种针对ucharts组件不同类型的可视化数据使用不同类型的h5界面的解决思路。