uniapp 多端兼容开发遇到的问题总结(四) ——专题:uView在弹出层里使用索引列表
前言在使用uView开发项目中,遇到了一个业务场景: 点击输入框弹出底部窗口,内置电话号码区号索引列表,点击切换区号 :当我根据逻辑以为在 u-popup 里加入 u-index-list 就行了,结果遇到问题了:索引列表滚动不了;选择索引字符,列表吸顶不了;瞄点与顶部距离有偏差。所以作者开始排查,但api文档没写相关用法,于是开始百度,但发现大家都在询问…(可能大家也百度过这类文章:https:
前言
在使用uView
开发项目中,遇到了一个业务场景: 点击输入框弹出底部窗口,内置电话号码区号索引列表,点击切换区号 :
当我根据逻辑以为在 u-popup 里加入 u-index-list 就行了,结果遇到问题了:
- 索引列表滚动不了;
- 选择索引字符,列表吸顶不了;
- 瞄点与顶部距离有偏差。
所以作者开始排查,但api文档没写相关用法,于是开始百度,但发现大家都在询问…(可能大家也百度过这类文章:https://ask.dcloud.net.cn/question/103729)
官网也没有合适满意的解决方案,于是作者只能去修改源码了…
1. 滚动不了
一开始很奇怪,看人家实例是可以滚动,但在u-popup
不行,原来文档写了onPageScroll
这个方法的,是针对整个页面去滚动的:
所以针对业务场景,这个方法就不适用了,首先是想到在u-popup
里面加入一层scroll-view
,但没用… 看文档得知原来组件里已内置了(还是要好好看文档呀~),所以这个也是无效的。
解决方法:监听弹出层的滚动,利用子组件把弹出层的scrollTop
传给父组件里的u-index-list
- 在u-popup组件里找到这段代码,添加事件scroll:
- 在方法里获取
u-popup
的scrollTop
: - 父组件再赋值:
2. 吸顶不了
首先找出目标代码,在u-index-list
里:
这里是针对整个页面去滚动吸顶的,所以同理把这段代码去掉,把容器距离顶部的高度传给父组件:
把u-popup
滚动高与容器的高度添加:
3. 高度偏差:
定位到目标代码:
备注: 修改源码前要先理解源码的逻辑噢~
然后根据你弹出层的高度进行增减就行啦。
下面是完整代码:
<u-popup :scrollTopBox="scrollTopBox" v-model="show" mode="bottom" height="1028rpx" @scroll="scroll">
<!-- tab -->
<view class="tabs">
<view class="tabs_wrapper">
<view class="tabs_wrapper_nav">
<view class="tabs"><text>国字区号</text></view>
<view class="tabs__line"></view>
</view>
<view class="cancel_button"><text @click="show = false">取消</text></view>
</view>
</view>
<u-index-list :scrollTop="scrollTop" @select="select" :index-list="indexList" activeColor="#e00202">
<view v-for="(item, index) in cityArr" :key="index">
<u-index-anchor :index="item.letter" />
<view class="list-cell" v-for="(item1, index) in item.data" :key="index" @click="selected(item1.code)">
<text>{{ item1.en }}</text>
<text>{{ item1.code }}</text>
</view>
</view>
</u-index-list>
</u-popup>
data() {
return {
show: false,
scrollTop: 0,
scrollTopBox: 0,
indexList: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'Y', 'Z'],
},
methods:{
scroll(val) {
// console.log(val)
this.scrollTop = val;
},
select(index) {
this.scrollTopBox = index + this.scrollTop;
},
}
u-popup
组件:
<template>
<view v-if="visibleSync" :style="[customStyle, {
zIndex: uZindex - 1
}]" class="u-drawer" hover-stop-propagation>
<u-mask :duration="duration" :custom-style="maskCustomStyle" :maskClickAble="maskCloseAble" :z-index="uZindex - 2" :show="showDrawer && mask" @click="maskClick"></u-mask>
<view
class="u-drawer-content"
@tap="modeCenterClose(mode)"
:class="[
safeAreaInsetBottom ? 'safe-area-inset-bottom' : '',
'u-drawer-' + mode,
showDrawer ? 'u-drawer-content-visible' : '',
zoom && mode == 'center' ? 'u-animation-zoom' : ''
]"
@touchmove.stop.prevent
@tap.stop.prevent
:style="[style]"
>
<view class="u-mode-center-box" @tap.stop.prevent @touchmove.stop.prevent v-if="mode == 'center'" :style="[centerStyle]">
<u-icon
@click="close"
v-if="closeable"
class="u-close"
:class="['u-close--' + closeIconPos]"
:name="closeIcon"
:color="closeIconColor"
:size="closeIconSize"
></u-icon>
<scroll-view class="u-drawer__scroll-view" scroll-y="true">
<slot />
</scroll-view>
</view>
<scroll-view class="u-drawer__scroll-view" scroll-y="true" :scroll-top="scrollTopBox" v-else @scroll="scroll">
<slot />
</scroll-view>
<view @tap="close" class="u-close" :class="['u-close--' + closeIconPos]">
<u-icon
v-if="mode != 'center' && closeable"
:name="closeIcon"
:color="closeIconColor"
:size="closeIconSize"
></u-icon>
</view>
</view>
</view>
</template>
<script>
import uMask from "../u-mask/u-mask.vue";
import zIndex from '../libs/config/zIndex.js';
/**
* popup 弹窗
* @description 弹出层容器,用于展示弹窗、信息提示等内容,支持上、下、左、右和中部弹出。组件只提供容器,内部内容由用户自定义
* @tutorial https://www.uviewui.com/components/popup.html
* @property {String} mode 弹出方向(默认left)
* @property {Boolean} mask 是否显示遮罩(默认true)
* @property {Stringr | Number} length mode=left | 见官网说明(默认auto)
* @property {Boolean} zoom 是否开启缩放动画,只在mode为center时有效(默认true)
* @property {Boolean} safe-area-inset-bottom 是否开启底部安全区适配(默认false)
* @property {Boolean} mask-close-able 点击遮罩是否可以关闭弹出层(默认true)
* @property {Object} custom-style 用户自定义样式
* @property {Stringr | Number} negative-top 中部弹出时,往上偏移的值
* @property {Numberr | String} border-radius 弹窗圆角值(默认0)
* @property {Numberr | String} z-index 弹出内容的z-index值(默认1075)
* @property {Boolean} closeable 是否显示关闭图标(默认false)
* @property {String} close-icon 关闭图标的名称,只能uView的内置图标
* @property {String} close-icon-pos 自定义关闭图标位置(默认top-right)
* @property {String} close-icon-color 关闭图标的颜色(默认#909399)
* @property {Number | String} close-icon-size 关闭图标的大小,单位rpx(默认30)
* @event {Function} open 弹出层打开
* @event {Function} close 弹出层收起
* @example <u-popup v-model="show"><view>出淤泥而不染,濯清涟而不妖</view></u-popup>
*/
export default {
components:{
uMask
},
name: 'u-popup',
props: {
// 滚动
scrollTopBox:{
type: Number,
default: 0
},
/**
* 显示状态
*/
show: {
type: Boolean,
default: false
},
/**
* 弹出方向,left|right|top|bottom|center
*/
mode: {
type: String,
default: 'left'
},
/**
* 是否显示遮罩
*/
mask: {
type: Boolean,
default: true
},
// 抽屉的宽度(mode=left|right),或者高度(mode=top|bottom),单位rpx,或者"auto"
// 或者百分比"50%",表示由内容撑开高度或者宽度
length: {
type: [Number, String],
default: 'auto'
},
// 是否开启缩放动画,只在mode=center时有效
zoom: {
type: Boolean,
default: true
},
// 是否开启底部安全区适配,开启的话,会在iPhoneX机型底部添加一定的内边距
safeAreaInsetBottom: {
type: Boolean,
default: false
},
// 是否可以通过点击遮罩进行关闭
maskCloseAble: {
type: Boolean,
default: true
},
// 用户自定义样式
customStyle: {
type: Object,
default() {
return {};
}
},
value: {
type: Boolean,
default: false
},
// 此为内部参数,不在文档对外使用,为了解决Picker和keyboard等融合了弹窗的组件
// 对v-model双向绑定多层调用造成报错不能修改props值的问题
popup: {
type: Boolean,
default: true
},
// 显示显示弹窗的圆角,单位rpx
borderRadius: {
type: [Number, String],
default: 0
},
zIndex: {
type: [Number, String],
default: ''
},
// 是否显示关闭图标
closeable: {
type: Boolean,
default: false
},
// 关闭图标的名称,只能uView的内置图标
closeIcon: {
type: String,
default: 'close'
},
// 自定义关闭图标位置,top-left为左上角,top-right为右上角,bottom-left为左下角,bottom-right为右下角
closeIconPos: {
type: String,
default: 'top-right'
},
// 关闭图标的颜色
closeIconColor: {
type: String,
default: '#909399'
},
// 关闭图标的大小,单位rpx
closeIconSize: {
type: [String, Number],
default: '30'
},
// 宽度,只对左,右,中部弹出时起作用,单位rpx,或者"auto"
// 或者百分比"50%",表示由内容撑开高度或者宽度,优先级高于length参数
width: {
type: String,
default: ''
},
// 高度,只对上,下,中部弹出时起作用,单位rpx,或者"auto"
// 或者百分比"50%",表示由内容撑开高度或者宽度,优先级高于length参数
height: {
type: String,
default: ''
},
// 给一个负的margin-top,往上偏移,避免和键盘重合的情况,仅在mode=center时有效
negativeTop: {
type: [String, Number],
default: 0
},
// 遮罩的样式,一般用于修改遮罩的透明度
maskCustomStyle: {
type: Object,
default() {
return {}
}
},
// 遮罩打开或收起的动画过渡时间,单位ms
duration: {
type: [String, Number],
default: 250
}
},
data() {
return {
visibleSync: false,
showDrawer: false,
timer: null,
closeFromInner: false, // value的值改变,是发生在内部还是外部
};
},
computed: {
// 根据mode的位置,设定其弹窗的宽度(mode = left|right),或者高度(mode = top|bottom)
style() {
let style = {};
// 如果是左边或者上边弹出时,需要给translate设置为负值,用于隐藏
if (this.mode == 'left' || this.mode == 'right') {
style = {
width: this.width ? this.getUnitValue(this.width) : this.getUnitValue(this.length),
height: '100%',
transform: `translate3D(${this.mode == 'left' ? '-100%' : '100%'},0px,0px)`
};
} else if (this.mode == 'top' || this.mode == 'bottom') {
style = {
width: '100%',
height: this.height ? this.getUnitValue(this.height) : this.getUnitValue(this.length),
transform: `translate3D(0px,${this.mode == 'top' ? '-100%' : '100%'},0px)`
};
}
style.zIndex = this.uZindex;
// 如果用户设置了borderRadius值,添加弹窗的圆角
if (this.borderRadius) {
switch (this.mode) {
case 'left':
style.borderRadius = `0 ${this.borderRadius}rpx ${this.borderRadius}rpx 0`;
break;
case 'top':
style.borderRadius = `0 0 ${this.borderRadius}rpx ${this.borderRadius}rpx`;
break;
case 'right':
style.borderRadius = `${this.borderRadius}rpx 0 0 ${this.borderRadius}rpx`;
break;
case 'bottom':
style.borderRadius = `${this.borderRadius}rpx ${this.borderRadius}rpx 0 0`;
break;
default:
}
// 不加可能圆角无效
style.overflow = 'hidden';
}
if(this.duration) style.transition = `all ${this.duration / 1000}s linear`;
return style;
},
// 中部弹窗的特有样式
centerStyle() {
let style = {};
style.width = this.width ? this.getUnitValue(this.width) : this.getUnitValue(this.length);
// 中部弹出的模式,如果没有设置高度,就用auto值,由内容撑开高度
style.height = this.height ? this.getUnitValue(this.height) : 'auto';
style.zIndex = this.uZindex;
style.marginTop = `-${this.$u.addUnit(this.negativeTop)}`;
if (this.borderRadius) {
style.borderRadius = `${this.borderRadius}rpx`;
// 不加可能圆角无效
style.overflow = 'hidden';
}
return style;
},
// 计算整理后的z-index值
uZindex() {
return this.zIndex ? this.zIndex : zIndex.popup;
}
},
watch: {
value(val) {
if (val) {
this.open();
} else if(!this.closeFromInner) {
this.close();
}
this.closeFromInner = false;
}
},
mounted() {
// 组件渲染完成时,检查value是否为true,如果是,弹出popup
this.value && this.open();
// console.log(this.scrollTopBox)
},
methods: {
// 判断传入的值,是否带有单位,如果没有,就默认用rpx单位
getUnitValue(val) {
if(/(%|px|rpx|auto)$/.test(val)) return val;
else return val + 'rpx'
},
scroll(e){
// console.log(e.detail.scrollTop)
this.$emit('scroll', e.detail.scrollTop);
},
// 遮罩被点击
maskClick() {
this.close();
},
close() {
// 标记关闭是内部发生的,否则修改了value值,导致watch中对value检测,导致再执行一遍close
// 造成@close事件触发两次
this.closeFromInner = true;
this.change('showDrawer', 'visibleSync', false);
},
// 中部弹出时,需要.u-drawer-content将居中内容,此元素会铺满屏幕,点击需要关闭弹窗
// 让其只在mode=center时起作用
modeCenterClose(mode) {
if (mode != 'center' || !this.maskCloseAble) return;
this.close();
},
open() {
this.change('visibleSync', 'showDrawer', true);
},
// 此处的原理是,关闭时先通过动画隐藏弹窗和遮罩,再移除整个组件
// 打开时,先渲染组件,延时一定时间再让遮罩和弹窗的动画起作用
change(param1, param2, status) {
// 如果this.popup为false,意味着为picker,actionsheet等组件调用了popup组件
if (this.popup == true) {
this.$emit('input', status);
}
this[param1] = status;
if(status) {
// #ifdef H5 || MP
this.timer = setTimeout(() => {
this[param2] = status;
this.$emit(status ? 'open' : 'close');
}, 50);
// #endif
// #ifndef H5 || MP
this.$nextTick(() => {
this[param2] = status;
this.$emit(status ? 'open' : 'close');
})
// #endif
} else {
this.timer = setTimeout(() => {
this[param2] = status;
this.$emit(status ? 'open' : 'close');
}, this.duration);
}
}
}
};
</script>
<style scoped lang="scss">
@import "../libs/css/style.components.scss";
.u-drawer {
/* #ifndef APP-NVUE */
display: block;
/* #endif */
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
overflow: hidden;
}
.u-drawer-content {
/* #ifndef APP-NVUE */
display: block;
/* #endif */
position: absolute;
z-index: 1003;
transition: all 0.25s linear;
}
.u-drawer__scroll-view {
width: 100%;
height: 100%;
}
.u-drawer-left {
top: 0;
bottom: 0;
left: 0;
background-color: #ffffff;
}
.u-drawer-right {
right: 0;
top: 0;
bottom: 0;
background-color: #ffffff;
}
.u-drawer-top {
top: 0;
left: 0;
right: 0;
background-color: #ffffff;
}
.u-drawer-bottom {
bottom: 0;
left: 0;
right: 0;
background-color: #ffffff;
}
.u-drawer-center {
@include vue-flex;
flex-direction: column;
bottom: 0;
left: 0;
right: 0;
top: 0;
justify-content: center;
align-items: center;
opacity: 0;
z-index: 99999;
}
.u-mode-center-box {
min-width: 100rpx;
min-height: 100rpx;
/* #ifndef APP-NVUE */
display: block;
/* #endif */
position: relative;
background-color: #ffffff;
}
.u-drawer-content-visible.u-drawer-center {
transform: scale(1);
opacity: 1;
}
.u-animation-zoom {
transform: scale(1.15);
}
.u-drawer-content-visible {
transform: translate3D(0px, 0px, 0px) !important;
}
.u-close {
position: absolute;
z-index: 3;
}
.u-close--top-left {
top: 30rpx;
left: 30rpx;
}
.u-close--top-right {
top: 30rpx;
right: 30rpx;
}
.u-close--bottom-left {
bottom: 30rpx;
left: 30rpx;
}
.u-close--bottom-right {
right: 30rpx;
bottom: 30rpx;
}
</style>
u-index-list
组件:
<template>
<!-- 支付宝小程序使用$u.getRect()获取组件的根元素尺寸,所以在外面套一个"壳" -->
<view>
<view class="u-index-bar">
<slot />
<view v-if="showSidebar" class="u-index-bar__sidebar" @touchstart.stop.prevent="onTouchMove" @touchmove.stop.prevent="onTouchMove"
@touchend.stop.prevent="onTouchStop" @touchcancel.stop.prevent="onTouchStop">
<view v-for="(item, index) in indexList" :key="index" class="u-index-bar__index" :style="{zIndex: zIndex + 1, color: activeAnchorIndex === index ? activeColor : ''}"
:data-index="index">
{{ item }}
</view>
</view>
<view class="u-indexed-list-alert" v-if="touchmove && indexList[touchmoveIndex]" :style="{
zIndex: alertZIndex
}">
<text>{{indexList[touchmoveIndex]}}</text>
</view>
</view>
</view>
</template>
<script>
import zIndex from '../libs/config/zIndex.js';
var indexList = function() {
var indexList = [];
var charCodeOfA = 'A'.charCodeAt(0);
for (var i = 0; i < 26; i++) {
indexList.push(String.fromCharCode(charCodeOfA + i));
}
return indexList;
};
/**
* indexList 索引列表
* @description 通过折叠面板收纳内容区域,搭配<u-index-anchor>使用
* @tutorial https://www.uviewui.com/components/indexList.html#indexanchor-props
* @property {Number String} scroll-top 当前滚动高度,自定义组件无法获得滚动条事件,所以依赖接入方传入
* @property {Array} index-list 索引字符列表,数组(默认A-Z)
* @property {Number String} z-index 锚点吸顶时的层级(默认965)
* @property {Boolean} sticky 是否开启锚点自动吸顶(默认true)
* @property {Number String} offset-top 锚点自动吸顶时与顶部的距离(默认0)
* @property {String} highlight-color 锚点和右边索引字符高亮颜色(默认#2979ff)
* @event {Function} select 选中右边索引字符时触发
* @example <u-index-list :scrollTop="scrollTop"></u-index-list>
*/
export default {
name: "u-index-list",
props: {
sticky: {
type: Boolean,
default: true
},
zIndex: {
type: [Number, String],
default: ''
},
scrollTop: {
type: [Number, String],
default: 0,
},
offsetTop: {
type: [Number, String],
default: 0
},
indexList: {
type: Array,
default () {
return indexList()
}
},
activeColor: {
type: String,
default: '#2979ff'
}
},
created() {
// #ifdef H5
this.stickyOffsetTop = this.offsetTop ? uni.upx2px(this.offsetTop) : 44;
// #endif
// #ifndef H5
this.stickyOffsetTop = this.offsetTop ? uni.upx2px(this.offsetTop) : 0;
// #endif
// 只能在created生命周期定义children,如果在data定义,会因为循环引用而报错
this.children = [];
},
data() {
return {
activeAnchorIndex: 0,
showSidebar: true,
// children: [],
touchmove: false,
touchmoveIndex: 0,
}
},
watch: {
scrollTop() {
this.updateData()
}
},
computed: {
// 弹出toast的z-index值
alertZIndex() {
return zIndex.toast;
}
},
methods: {
updateData() {
this.timer && clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.showSidebar = !!this.children.length;
this.setRect().then(() => {
this.onScroll();
});
}, 0);
},
setRect() {
return Promise.all([
this.setAnchorsRect(),
this.setListRect(),
this.setSiderbarRect()
]);
},
setAnchorsRect() {
return Promise.all(this.children.map((anchor, index) => anchor
.$uGetRect('.u-index-anchor-wrapper')
.then((rect) => {
Object.assign(anchor, {
height: rect.height,
top: rect.top
});
})));
},
setListRect() {
return this.$uGetRect('.u-index-bar').then((rect) => {
Object.assign(this, {
height: rect.height,
top: rect.top + this.scrollTop
});
});
},
setSiderbarRect() {
return this.$uGetRect('.u-index-bar__sidebar').then(rect => {
this.sidebar = {
height: rect.height,
top: rect.top
};
});
},
getActiveAnchorIndex() {
const {
children
} = this;
const {
sticky
} = this;
for (let i = this.children.length - 1; i >= 0; i--) {
let itemTop = children[i].top - 100;
const preAnchorHeight = i > 0 ? children[i - 1].height : 0;
const reachTop = sticky ? preAnchorHeight : 0;
// console.log(reachTop)
if (reachTop >= itemTop) {
return i;
}
}
return -1;
},
onScroll() {
const {
children = []
} = this;
if (!children.length) {
return;
}
const {
sticky,
stickyOffsetTop,
zIndex,
scrollTop,
activeColor
} = this;
const active = this.getActiveAnchorIndex();
this.activeAnchorIndex = active;
if (sticky) {
let isActiveAnchorSticky = false;
if (active !== -1) {
isActiveAnchorSticky =
children[active].top - 100 <= 0;
}
children.forEach((item, index) => {
if (index === active) {
let wrapperStyle = '';
let anchorStyle = {
color: `${activeColor}`
};
if (isActiveAnchorSticky) {
wrapperStyle = {
height: `${children[index].height}px`
};
anchorStyle = {
position: 'fixed',
top: `${stickyOffsetTop}px`,
zIndex: `${zIndex ? zIndex : zIndex.indexListSticky}`,
color: `${activeColor}`
};
}
item.active = active;
item.wrapperStyle = wrapperStyle;
item.anchorStyle = anchorStyle;
} else if (index === active - 1) {
const currentAnchor = children[index];
const currentOffsetTop = currentAnchor.top;
const targetOffsetTop = index === children.length - 1 ?
this.top :
children[index + 1].top;
const parentOffsetHeight = targetOffsetTop - currentOffsetTop;
const translateY = parentOffsetHeight - currentAnchor.height;
const anchorStyle = {
position: 'relative',
transform: `translate3d(0, ${translateY}px, 0)`,
zIndex: `${zIndex ? zIndex : zIndex.indexListSticky}`,
color: `${activeColor}`
};
item.active = active;
item.anchorStyle = anchorStyle;
} else {
item.active = false;
item.anchorStyle = '';
item.wrapperStyle = '';
}
});
}
},
onTouchMove(event) {
this.touchmove = true;
const sidebarLength = this.children.length;
const touch = event.touches[0];
const itemHeight = this.sidebar.height / sidebarLength;
let clientY = 0;
clientY = touch.clientY;
let index = Math.floor((clientY - this.sidebar.top) / itemHeight);
if (index < 0) {
index = 0;
} else if (index > sidebarLength - 1) {
index = sidebarLength - 1;
}
this.touchmoveIndex = index;
this.scrollToAnchor(index);
},
onTouchStop() {
this.touchmove = false;
this.scrollToAnchorIndex = null;
},
scrollToAnchor(index) {
if (this.scrollToAnchorIndex === index) {
return;
}
this.scrollToAnchorIndex = index;
const anchor = this.children.find((item) => item.index === this.indexList[index]);
if (anchor) {
this.$emit('select', anchor.top);
// uni.pageScrollTo({
// duration: 0,
// scrollTop: anchor.top + this.scrollTop
// });
}
}
}
};
</script>
<style lang="scss" scoped>
@import "../libs/css/style.components.scss";
.u-index-bar {
margin-top: 45px;
position: relative
}
.u-index-bar__sidebar {
position: fixed;
top: 304px;
right: 0;
@include vue-flex;
flex-direction: column;
text-align: center;
transform: translateY(-50%);
user-select: none;
z-index: 99;
background-color: #c8c8c8;
font-family: Helvetica;
width: 24px;
}
.u-index-bar__index {
font-weight: 500;
padding: 8rpx;
font-size: 22rpx;
line-height: 1;
color: hsla(0,0%,100%,.5);
}
.u-indexed-list-alert {
position: fixed;
width: 120rpx;
height: 120rpx;
right: 90rpx;
top: 50%;
margin-top: -60rpx;
border-radius: 24rpx;
font-size: 50rpx;
color: #fff;
background-color: rgba(0, 0, 0, 0.65);
@include vue-flex;
justify-content: center;
align-items: center;
padding: 0;
z-index: 9999999;
}
.u-indexed-list-alert text {
line-height: 50rpx;
}
</style>
更多推荐
所有评论(0)