u-tabs.vue 13 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
<template>
	<view class="u-tabs" :class="[customClass]">
		<view class="u-tabs__wrapper">
			<slot name="left" />
			<view class="u-tabs__wrapper__scroll-view-wrapper">
				<scroll-view
					:scroll-x="scrollable"
					:scroll-left="scrollLeft"
					scroll-with-animation
					class="u-tabs__wrapper__scroll-view"
					:show-scrollbar="false"
					ref="u-tabs__wrapper__scroll-view"
				>
					<view
						class="u-tabs__wrapper__nav"
						ref="u-tabs__wrapper__nav"
					>
						<view
							class="u-tabs__wrapper__nav__item"
							v-for="(item, index) in list"
							:key="index"
							@tap="clickHandler(item, index)"
							@longpress="longPressHandler(item,index)"
							:ref="`u-tabs__wrapper__nav__item-${index}`"
							:style="[addStyle(itemStyle), {flex: scrollable ? '' : 1}]"
							:class="[`u-tabs__wrapper__nav__item-${index}`,
								item.disabled && 'u-tabs__wrapper__nav__item--disabled',
								innerCurrent == index ? 'u-tabs__wrapper__nav__item-active' : '']"
						>
							<slot v-if="$slots.icon" name="icon" :item="item" :keyName="keyName" :index="index" />
							<template v-else>
								<view class="u-tabs__wrapper__nav__item__prefix-icon" v-if="item.icon">
									<up-icon
										:name="item.icon"
										:customStyle="addStyle(iconStyle)"
									></up-icon>
								</view>
							</template>
							<slot v-if="$slots.content" name="content" :item="item" :keyName="keyName" :index="index" />
							<slot v-else-if="!$slots.content && ($slots.default || $slots.$default)"
								:item="item" :keyName="keyName" :index="index" />
							<text v-else
								:class="[item.disabled && 'u-tabs__wrapper__nav__item__text--disabled']"
								class="u-tabs__wrapper__nav__item__text"
								:style="[textStyle(index)]"
							>{{ item[keyName] }}</text>
							<u-badge
								:show="!!(item.badge && (item.badge.show || item.badge.isDot || item.badge.value))"
								:isDot="item.badge && item.badge.isDot || propsBadge.isDot"
								:value="item.badge && item.badge.value || propsBadge.value"
								:max="item.badge && item.badge.max || propsBadge.max"
								:type="item.badge && item.badge.type || propsBadge.type"
								:showZero="item.badge && item.badge.showZero || propsBadge.showZero"
								:bgColor="item.badge && item.badge.bgColor || propsBadge.bgColor"
								:color="item.badge && item.badge.color || propsBadge.color"
								:shape="item.badge && item.badge.shape || propsBadge.shape"
								:numberType="item.badge && item.badge.numberType || propsBadge.numberType"
								:inverted="item.badge && item.badge.inverted || propsBadge.inverted"
								customStyle="margin-left: 4px;"
							></u-badge>
						</view>
						<!-- #ifdef APP-NVUE -->
						<view
							class="u-tabs__wrapper__nav__line"
							ref="u-tabs__wrapper__nav__line"
							:style="[{
								width: addUnit(lineWidth),
								height: addUnit(lineHeight),
								background: lineColor,
								backgroundSize: lineBgSize,
							}]"
						>
						</view>
						<!-- #endif -->
						<!-- #ifndef APP-NVUE -->
						<view
							class="u-tabs__wrapper__nav__line"
							ref="u-tabs__wrapper__nav__line"
							:style="[{
								width: addUnit(lineWidth),
								transform: `translate(${lineOffsetLeft}px)`,
								transitionDuration: `${firstTime ? 0 : duration}ms`,
								height: addUnit(lineHeight),
								background: lineColor,
								backgroundSize: lineBgSize,
							}]"
						>
						</view>
						<!-- #endif -->
					</view>
				</scroll-view>
			</view>
			<slot name="right" />
		</view>
	</view>
</template>

<script>
	// #ifdef APP-NVUE
	const animation = uni.requireNativePlugin('animation')
	const dom = uni.requireNativePlugin('dom')
	// #endif
	import { props } from './props';
	import { mpMixin } from '../../libs/mixin/mpMixin';
	import { mixin } from '../../libs/mixin/mixin';
	import defProps from '../../libs/config/props.js'
	import { addUnit, addStyle, deepMerge, getPx, sleep, getWindowInfo } from '../../libs/function/index';
	/**
	 * Tabs 标签
	 * @description tabs标签组件,在标签多的时候,可以配置为左右滑动,标签少的时候,可以禁止滑动。 该组件的一个特点是配置为滚动模式时,激活的tab会自动移动到组件的中间位置。
	 * @tutorial https://uview-plus.jiangruyi.com/components/tabs.html
	 * @property {String | Number}	duration			滑块移动一次所需的时间,单位秒(默认 200 )
	 * @property {String | Number}	swierWidth			swiper的宽度(默认 '750rpx' )
	 * @property {String}	keyName	 从`list`元素对象中读取的键名(默认 'name' )
	 * @event {Function(index)} change 标签改变时触发 index: 点击了第几个tab,索引从0开始
	 * @event {Function(index)} click 点击标签时触发 index: 点击了第几个tab,索引从0开始
	 * @event {Function(index)} longPress 长按标签时触发 index: 点击了第几个tab,索引从0开始
	 * @example <u-tabs :list="list" :is-scroll="false" :current="current" @change="change" @longPress="longPress"></u-tabs>
	 */
	export default {
		name: 'u-tabs',
		mixins: [mpMixin, mixin, props],
		data() {
			return {
				firstTime: true,
				scrollLeft: 0,
				scrollViewWidth: 0,
				lineOffsetLeft: 0,
				tabsRect: {
					left: 0
				},
				innerCurrent: 0,
				moving: false,
			}
		},
		watch: {
			current: {
				immediate: true,
				handler (newValue, oldValue) {
					// 内外部值不相等时,才尝试移动滑块
					if (newValue !== this.innerCurrent) {
						if (typeof newValue == 'string') {
							this.innerCurrent = parseInt(newValue)
						} else {
							this.innerCurrent = newValue
						}
						this.$nextTick(() => {
							this.resize()
						})
					}
				}
			},
			// list变化时,重新渲染list各项信息
			list() {
				this.$nextTick(() => {
					this.resize()
				})
			}
		},
		computed: {
			textStyle() {
				return index => {
					const style = {}
					// 取当期是否激活的样式
					const customeStyle = (index == this.innerCurrent)
						? addStyle(this.activeStyle) 
						: addStyle(this.inactiveStyle)
					// 如果当前菜单被禁用,则加上对应颜色,需要在此做处理,是因为nvue下,无法在style样式中通过!import覆盖标签的内联样式
					if (this.list[index].disabled) {
						style.color = '#c8c9cc'
					}
					return deepMerge(customeStyle, style)
				}
			},
			propsBadge() {
				return defProps.badge
			}
		},
		async mounted() {
			this.init()
            this.windowResizeCallback = (res) => {
                this.init()
            }
            uni.onWindowResize(this.windowResizeCallback)
		},
        beforeUnmount() {
            uni.offWindowResize(this.windowResizeCallback)
        },
		emits: ['click', 'longPress', 'change', 'update:current'],
		methods: {
			addStyle,
			addUnit,
			setLineLeft() {
				const tabItem = this.list[this.innerCurrent];
				if (!tabItem) {
					return;
				}
				// 获取滑块该移动的位置
				let lineOffsetLeft = this.list
					.slice(0, this.innerCurrent)
					.reduce((total, curr) => total + curr.rect.width, 0);
                // 获取下划线的数值px表示法
				const lineWidth = getPx(this.lineWidth);
				this.lineOffsetLeft = lineOffsetLeft + (tabItem.rect.width - lineWidth) / 2
				// #ifdef APP-NVUE
				// 第一次移动滑块,无需过渡时间
				this.animation(this.lineOffsetLeft, this.firstTime ? 0 : parseInt(this.duration))
				// #endif

				// 如果是第一次执行此方法,让滑块在初始化时,瞬间滑动到第一个tab item的中间
				// 这里需要一个定时器,因为在非nvue下,是直接通过style绑定过渡时间,需要等其过渡完成后,再设置为false(非第一次移动滑块)
				if (this.firstTime) {
					setTimeout(() => {
						this.firstTime = false
					}, 10);
				}
			},
			// nvue下设置滑块的位置
			animation(x, duration = 0) {
				// #ifdef APP-NVUE
				const ref = this.$refs['u-tabs__wrapper__nav__line']
				animation.transition(ref, {
					styles: {
						transform: `translateX(${x}px)`
					},
					duration
				})
				// #endif
			},
			// 点击某一个标签
			clickHandler(item, index) {
				// 因为标签可能为disabled状态,所以click是一定会发出的,但是change事件是需要可用的状态才发出
				this.$emit('click', {
					...item,
					index
				}, index)
				// 如果disabled状态,返回
				if (item.disabled) return
				// 如果点击当前不触发change
				if (this.innerCurrent == index) return
				this.innerCurrent = index
                this.$nextTick(() => {
                    this.resize()
                })
				this.$emit('update:current', index)
				this.$emit('change', {
					...item,
					index
				}, index)
			},
			// 长按事件
			longPressHandler(item, index) {
				this.$emit('longPress', {
					...item,
					index
				})
			},
			init() {
				sleep().then(() => {
					this.resize()
				})
			},
			setScrollLeft() {
				// 当前活动tab的布局信息,有tab菜单的width和left(为元素左边界到父元素左边界的距离)等信息
				if (this.innerCurrent < 0) {
                    this.innerCurrent = 0;
                }
				const tabRect = this.list[this.innerCurrent]
				// 累加得到当前item到左边的距离
				const offsetLeft = this.list
					.slice(0, this.innerCurrent)
					.reduce((total, curr) => {
						return total + curr.rect.width
					}, 0)
				// 此处为屏幕宽度
				const windowWidth = getWindowInfo().windowWidth
				// 将活动的tabs-item移动到屏幕正中间,实际上是对scroll-view的移动
				let scrollLeft = offsetLeft - (this.tabsRect.width - tabRect.rect.width) / 2 - (windowWidth - this.tabsRect
					.right) / 2 + this.tabsRect.left / 2
				// 这里做一个限制,限制scrollLeft的最大值为整个scroll-view宽度减去tabs组件的宽度
				scrollLeft = Math.min(scrollLeft, this.scrollViewWidth - this.tabsRect.width)
				this.scrollLeft = Math.max(0, scrollLeft)
			},
			// 获取所有标签的尺寸
			resize() {
				// 如果不存在list,则不处理
				if(this.list.length === 0) {
					return
				}
				Promise.all([this.getTabsRect(), this.getAllItemRect()]).then(([tabsRect, itemRect = []]) => {
					// 兼容在swiper组件中使用
					if (tabsRect.left > tabsRect.width) {
						tabsRect.right = tabsRect.right - Math.floor(tabsRect.left / tabsRect.width) * tabsRect.width
						tabsRect.left = tabsRect.left % tabsRect.width
					}
					// console.log(tabsRect)
					this.tabsRect = tabsRect
					this.scrollViewWidth = 0
					itemRect.map((item, index) => {
						// 计算scroll-view的宽度,这里
						this.scrollViewWidth += item.width
						// 另外计算每一个item的中心点X轴坐标
						this.list[index].rect = item
					})
					// 获取了tabs的尺寸之后,设置滑块的位置
					this.setLineLeft()
					this.setScrollLeft()
				})
			},
			// 获取导航菜单的尺寸
			getTabsRect() {
				return new Promise(resolve => {
					this.queryRect('u-tabs__wrapper__scroll-view').then(size => resolve(size))
				})
			},
			// 获取所有标签的尺寸
			getAllItemRect() {
				return new Promise(resolve => {
					const promiseAllArr = this.list.map((item, index) => this.queryRect(
						`u-tabs__wrapper__nav__item-${index}`, true))
					Promise.all(promiseAllArr).then(sizes => resolve(sizes))
				})
			},
			// 获取各个标签的尺寸
			queryRect(el, item) {
				// #ifndef APP-NVUE
				// $uGetRect为uView自带的节点查询简化方法,详见文档介绍:https://uview-plus.jiangruyi.com/js/getRect.html
				// 组件内部一般用this.$uGetRect,对外的为uni.$u.getRect,二者功能一致,名称不同
				return new Promise(resolve => {
					this.$uGetRect(`.${el}`).then(size => {
						resolve(size)
					})
				})
				// #endif

				// #ifdef APP-NVUE
				// nvue下,使用dom模块查询元素高度
				// 返回一个promise,让调用此方法的主体能使用then回调
				return new Promise(resolve => {
					dom.getComponentRect(item ? this.$refs[el][0] : this.$refs[el], res => {
						resolve(res.size)
					})
				})
				// #endif
			},
		},
	}
</script>

<style lang="scss" scoped>

	.u-tabs {

		&__wrapper {
			@include flex;
			align-items: center;

			&__scroll-view-wrapper {
				flex: 1;
				/* #ifndef APP-NVUE */
				overflow: auto hidden;
				/* #endif */
			}

			&__scroll-view {
				@include flex;
				flex: 1;
			}

			&__nav {
				@include flex;
				position: relative;

				&__item {
					padding: 0 11px;
					@include flex;
					align-items: center;
					justify-content: center;
					/* #ifdef H5 */
					cursor: pointer;
					/* #endif */

					&--disabled {
						/* #ifdef H5 */
						cursor: not-allowed;
						/* #endif */
					}

					&__text {
						font-size: 15px;
						color: $u-content-color;
                        white-space: nowrap !important;

						&--disabled {
							color: $u-disabled-color !important;
						}
					}
				}

				&__line {
					height: 3px;
					background: $u-primary;
					width: 30px;
					position: absolute;
					bottom: 2px;
					border-radius: 100px;
					transition-property: transform;
					transition-duration: 300ms;
				}
			}
		}
	}
</style>