u-tabs.vue 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. <template>
  2. <view class="u-tabs">
  3. <view class="u-tabs__wrapper">
  4. <slot name="left" />
  5. <view class="u-tabs__wrapper__scroll-view-wrapper">
  6. <scroll-view
  7. :scroll-x="scrollable"
  8. :scroll-left="scrollLeft"
  9. scroll-with-animation
  10. class="u-tabs__wrapper__scroll-view"
  11. :show-scrollbar="false"
  12. ref="u-tabs__wrapper__scroll-view"
  13. >
  14. <view
  15. class="u-tabs__wrapper__nav"
  16. ref="u-tabs__wrapper__nav"
  17. >
  18. <view
  19. class="u-tabs__wrapper__nav__item"
  20. v-for="(item, index) in computedList"
  21. :key="index"
  22. @tap="clickHandler(item, index)"
  23. @longpress="longPressHandler(item,index)"
  24. :ref="`u-tabs__wrapper__nav__item-${index}`"
  25. :style="[$u.addStyle(itemStyle), {flex: scrollable ? '' : 1}]"
  26. :class="[`u-tabs__wrapper__nav__item-${index}`, item.disabled && 'u-tabs__wrapper__nav__item--disabled']"
  27. >
  28. <text
  29. :class="[item.disabled && 'u-tabs__wrapper__nav__item__text--disabled']"
  30. class="u-tabs__wrapper__nav__item__text"
  31. :style="[textStyle(index)]"
  32. >{{ item[keyName] }}</text>
  33. <u-badge
  34. :show="!!(item.badge && (item.badge.show || item.badge.isDot || item.badge.value))"
  35. :isDot="item.badge && item.badge.isDot"
  36. :value="item.badge && item.badge.value "
  37. :max="item.badge && item.badge.max"
  38. :type="item.badge && item.badge.type"
  39. :showZero="item.badge && item.badge.showZero"
  40. :bgColor="item.badge && item.badge.bgColor"
  41. :color="item.badge && item.badge.color"
  42. :shape="item.badge && item.badge.shape"
  43. :numberType="item.badge && item.badge.numberType"
  44. :inverted="item.badge && item.badge.inverted"
  45. customStyle="margin-left: 4px;"
  46. ></u-badge>
  47. </view>
  48. <!-- #ifdef APP-NVUE -->
  49. <view
  50. class="u-tabs__wrapper__nav__line"
  51. ref="u-tabs__wrapper__nav__line"
  52. :style="[{
  53. width: $u.addUnit(lineWidth),
  54. height: $u.addUnit(lineHeight),
  55. background: lineColor,
  56. backgroundSize: lineBgSize,
  57. }]"
  58. >
  59. <!-- #endif -->
  60. <!-- #ifndef APP-NVUE -->
  61. <view
  62. class="u-tabs__wrapper__nav__line"
  63. ref="u-tabs__wrapper__nav__line"
  64. :style="[{
  65. width: $u.addUnit(lineWidth),
  66. transform: `translate(${lineOffsetLeft}px)`,
  67. transitionDuration: `${firstTime ? 0 : duration}ms`,
  68. height: $u.addUnit(lineHeight),
  69. background: lineColor,
  70. backgroundSize: lineBgSize,
  71. }]"
  72. >
  73. <!-- #endif -->
  74. </view>
  75. </view>
  76. </scroll-view>
  77. </view>
  78. <slot name="right" />
  79. </view>
  80. <view class="u-tabs__content" v-if="isSlot" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd" @touchcancel="onTouchEnd">
  81. <view
  82. class="u-tabs__content__body"
  83. :class="[animated ? 'u-tabs__content__body--animated' : '']"
  84. :style="contentBodyStyle"
  85. >
  86. <slot />
  87. </view>
  88. </view>
  89. </view>
  90. </template>
  91. <script>
  92. // #ifdef APP-NVUE
  93. const animation = uni.requireNativePlugin('animation')
  94. const dom = uni.requireNativePlugin('dom')
  95. // #endif
  96. import props from './props.js';
  97. import mixin from '../../libs/mixin/mixin'
  98. import mpMixin from '../../libs/mixin/mpMixin';
  99. /**
  100. * Tabs 标签
  101. * @description tabs标签组件,在标签多的时候,可以配置为左右滑动,标签少的时候,可以禁止滑动。激活的tab会自动移动到组件的中间位置。
  102. * @tutorial https://uview.d3u.cn/components/tabs.html
  103. *
  104. * @property {Number} duration 滑块/内容动画过渡时间(ms),默认 300
  105. * @property {Boolean} animated 是否启用转场动画,默认 false
  106. * @property {Boolean} swipeable 是否启用左右滑动切换,默认 false
  107. * @property {String|Number} height 内容区域固定高度,默认 ''(自适应)
  108. * @property {Array} list tabs标签数组,默认 []
  109. * @property {String} lineColor 滑块颜色,默认主题色
  110. * @property {String|Object} activeStyle 选中项文字样式,默认 { color: theme.contentColor }
  111. * @property {String|Object} inactiveStyle 未选中项文字样式,默认 { color: theme.lightColor }
  112. * @property {String|Number} lineWidth 滑块长度,默认 20
  113. * @property {String|Number} lineHeight 滑块高度,默认 3
  114. * @property {String} lineBgSize 滑块背景显示大小(背景为图片时使用),默认 'cover'
  115. * @property {String|Object} itemStyle 菜单item样式,默认 { height: '44px' }
  116. * @property {Boolean} scrollable 菜单是否可滚动,默认 true
  117. * @property {Number|String} current 当前选中标签索引/标识,默认 0
  118. * @property {String} keyName 从 list 元素对象中读取标题的键名,默认 'name'
  119. *
  120. * @event {Function} change 标签改变时触发,参数 { index }
  121. * @event {Function} click 点击标签时触发,参数 { index }
  122. * @event {Function} longPress 长按标签时触发,参数 { index }
  123. *
  124. * @example <u-tabs :list="list" :scrollable="false" :current="current" @change="change" @longPress="longPress"></u-tabs>
  125. */
  126. export default {
  127. name: 'u-tabs',
  128. mixins: [mpMixin, mixin, props],
  129. data() {
  130. return {
  131. swiperCurrent: 0,
  132. isSlot: false,
  133. firstTime: true,
  134. scrollLeft: 0,
  135. scrollViewWidth: 0,
  136. lineOffsetLeft: 0,
  137. tabsRect: {
  138. left: 0
  139. },
  140. innerCurrent: 0,
  141. moving: false,
  142. children: [],
  143. // 触摸相关状态(精简为一个对象)
  144. touch: {
  145. startX: 0,
  146. startY: 0,
  147. deltaX: 0,
  148. deltaY: 0,
  149. offsetX: 0,
  150. offsetY: 0,
  151. direction: ''
  152. },
  153. dragging: false,
  154. dragOffsetPct: 0
  155. }
  156. },
  157. watch: {
  158. current: {
  159. immediate: true,
  160. handler (newValue, oldValue) {
  161. // 内外部值不相等时,才尝试移动滑块
  162. if (newValue !== this.innerCurrent) {
  163. // 如果使用子组件方式,需要根据name或index来匹配
  164. if (this.list && this.list.length > 0) {
  165. // 使用list方式,直接使用数字索引
  166. this.innerCurrent = parseInt(newValue)
  167. } else {
  168. // 使用子组件方式,需要找到对应的索引
  169. const index = this.children.findIndex((child, idx) => {
  170. return (child.name !== null && child.name !== undefined) ? child.name === newValue : idx === newValue
  171. })
  172. this.innerCurrent = index >= 0 ? index : 0
  173. }
  174. this.$nextTick(() => {
  175. this.resize()
  176. })
  177. }
  178. }
  179. },
  180. // list变化时,重新渲染list各项信息
  181. list() {
  182. this.$nextTick(() => {
  183. this.resize()
  184. })
  185. },
  186. // 监听子组件变化
  187. children() {
  188. this.$nextTick(() => {
  189. this.resize()
  190. })
  191. }
  192. },
  193. computed: {
  194. // 计算最终的list,优先使用list属性,如果没有则使用子组件生成的list
  195. computedList() {
  196. if (this.list && this.list.length > 0) {
  197. return this.list
  198. }
  199. this.isSlot = true
  200. // 从子组件生成list
  201. return this.children.map((child, index) => {
  202. return {
  203. [this.keyName]: child.label,
  204. disabled: child.disabled || false,
  205. badge: {
  206. isDot: child.dot,
  207. value: child.badge
  208. }
  209. }
  210. })
  211. },
  212. textStyle() {
  213. return index => {
  214. const style = {}
  215. // 取当期是否激活的样式
  216. const customeStyle = index === this.innerCurrent ? uni.$u.addStyle(this.activeStyle) : uni.$u.addStyle(this.inactiveStyle)
  217. // 如果当前菜单被禁用,则加上对应颜色,需要在此做处理,是因为nvue下,无法在style样式中通过!import覆盖标签的内联样式
  218. if (this.computedList[index].disabled) {
  219. style.color = '#c8c9cc'
  220. }
  221. return uni.$u.deepMerge(customeStyle, style)
  222. }
  223. },
  224. contentBodyStyle() {
  225. if (!this.animated) {
  226. return {}
  227. }
  228. const baseLeft = -100 * this.innerCurrent
  229. let style = {
  230. left: (baseLeft + (this.dragging ? this.dragOffsetPct : 0)) + '%',
  231. transitionDuration: (this.dragging ? 0 : this.duration) + 'ms',
  232. '-webkit-transition-duration': (this.dragging ? 0 : this.duration) + 'ms'
  233. }
  234. if(this.height) {
  235. style.height = uni.$u.addUnit(this.height)
  236. }
  237. // 根据方向确定是否对 left 应用过渡,以及切换不同的缓动(左/右)
  238. const isHorizontal = this.touch.direction === 'horizontal'
  239. const isRight = isHorizontal && this.touch.deltaX > 0
  240. const isLeft = isHorizontal && this.touch.deltaX < 0
  241. style.transitionProperty = isHorizontal || !this.touch.direction ? 'left' : 'none'
  242. style.transitionTimingFunction = this.dragging
  243. ? 'linear'
  244. : (isLeft
  245. ? 'cubic-bezier(0.4, 0, 0.2, 1)'
  246. : (isRight ? 'cubic-bezier(0.2, 0, 0, 1)' : 'cubic-bezier(0.4, 0, 0.2, 1)'))
  247. return style
  248. }
  249. },
  250. created() {
  251. this.children = []
  252. },
  253. async mounted() {
  254. this.init()
  255. //#ifndef MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-HARMONY
  256. uni.onWindowResize(this.windowResize)
  257. //#endif
  258. },
  259. beforeUnmount() {
  260. //#ifndef MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-HARMONY
  261. uni.offWindowResize(this.windowResize)
  262. //#endif
  263. },
  264. // #ifdef VUE3
  265. emits: ["click", "longPress", "change"],
  266. // #endif
  267. methods: {
  268. // 更新子组件
  269. updateChildren() {
  270. this.children.forEach((child, index) => {
  271. child.updateFromParent()
  272. })
  273. },
  274. setLineLeft() {
  275. const tabItem = this.computedList[this.innerCurrent];
  276. if (!tabItem || !tabItem.rect) {
  277. return;
  278. }
  279. // 获取滑块该移动的位置
  280. let lineOffsetLeft = this.computedList
  281. .slice(0, this.innerCurrent)
  282. .reduce((total, curr) => total + (curr.rect ? curr.rect.width : 0), 0);
  283. // 获取下划线的数值px表示法
  284. const lineWidth = uni.$u.getPx(this.lineWidth);
  285. this.lineOffsetLeft = lineOffsetLeft + (tabItem.rect.width - lineWidth) / 2
  286. // #ifdef APP-NVUE
  287. // 第一次移动滑块,无需过渡时间
  288. this.animation(this.lineOffsetLeft, this.firstTime ? 0 : parseInt(this.duration))
  289. // #endif
  290. // 如果是第一次执行此方法,让滑块在初始化时,瞬间滑动到第一个tab item的中间
  291. // 这里需要一个定时器,因为在非nvue下,是直接通过style绑定过渡时间,需要等其过渡完成后,再设置为false(非第一次移动滑块)
  292. if (this.firstTime) {
  293. setTimeout(() => {
  294. this.firstTime = false
  295. }, 10);
  296. }
  297. },
  298. // nvue下设置滑块的位置
  299. animation(x, duration = 0) {
  300. // #ifdef APP-NVUE
  301. const ref = this.$refs['u-tabs__wrapper__nav__line']
  302. animation.transition(ref, {
  303. styles: {
  304. transform: `translateX(${x}px)`
  305. },
  306. duration
  307. })
  308. // #endif
  309. },
  310. // 点击某一个标签
  311. clickHandler(item, index) {
  312. // 因为标签可能为disabled状态,所以click是一定会发出的,但是change事件是需要可用的状态才发出
  313. this.$emit('click', {
  314. ...item,
  315. index
  316. })
  317. // 如果disabled状态,返回
  318. if (item.disabled) return
  319. this.innerCurrent = index
  320. this.resize()
  321. this.$emit('change', {
  322. ...item,
  323. index
  324. })
  325. // 更新子组件状态
  326. this.updateChildren()
  327. },
  328. // 长按事件
  329. longPressHandler(item, index) {
  330. this.$emit('longPress', {
  331. ...item,
  332. index
  333. })
  334. },
  335. init() {
  336. uni.$u.sleep().then(() => {
  337. this.resize()
  338. })
  339. },
  340. windowResize() {
  341. this.init()
  342. },
  343. setScrollLeft() {
  344. // 当前活动tab的布局信息,有tab菜单的width和left(为元素左边界到父元素左边界的距离)等信息
  345. if (this.innerCurrent < 0) {
  346. this.innerCurrent = 0;
  347. }
  348. const tabRect = this.computedList[this.innerCurrent]
  349. // 如果tabRect不存在或者没有rect属性,则不处理
  350. if (!tabRect || !tabRect.rect) {
  351. return
  352. }
  353. // 累加得到当前item到左边的距离
  354. const offsetLeft = this.computedList
  355. .slice(0, this.innerCurrent)
  356. .reduce((total, curr) => {
  357. return total + (curr.rect ? curr.rect.width : 0)
  358. }, 0)
  359. // 此处为屏幕宽度
  360. const windowWidth = uni.$u.window().windowWidth
  361. // 将活动的tabs-item移动到屏幕正中间,实际上是对scroll-view的移动
  362. let scrollLeft = offsetLeft - (this.tabsRect.width - tabRect.rect.width) / 2 - (windowWidth - this.tabsRect
  363. .right) / 2 + this.tabsRect.left / 2
  364. // 这里做一个限制,限制scrollLeft的最大值为整个scroll-view宽度减去tabs组件的宽度
  365. scrollLeft = Math.min(scrollLeft, this.scrollViewWidth - this.tabsRect.width)
  366. this.scrollLeft = Math.max(0, scrollLeft)
  367. },
  368. // 获取所有标签的尺寸
  369. resize() {
  370. // 如果不存在list,则不处理
  371. if(this.computedList.length === 0) {
  372. return
  373. }
  374. Promise.all([this.getTabsRect(), this.getAllItemRect()]).then(([tabsRect, itemRect = []]) => {
  375. this.tabsRect = tabsRect
  376. this.scrollViewWidth = 0
  377. itemRect.map((item, index) => {
  378. // 计算scroll-view的宽度,这里
  379. this.scrollViewWidth += item.width
  380. // 另外计算每一个item的中心点X轴坐标
  381. this.computedList[index].rect = item
  382. })
  383. // 获取了tabs的尺寸之后,设置滑块的位置
  384. this.setLineLeft()
  385. this.setScrollLeft()
  386. })
  387. },
  388. // 获取导航菜单的尺寸
  389. getTabsRect() {
  390. return new Promise(resolve => {
  391. this.queryRect('u-tabs__wrapper__scroll-view').then(size => resolve(size))
  392. })
  393. },
  394. // 获取所有标签的尺寸
  395. getAllItemRect() {
  396. return new Promise(resolve => {
  397. const promiseAllArr = this.computedList.map((item, index) => this.queryRect(
  398. `u-tabs__wrapper__nav__item-${index}`, true))
  399. Promise.all(promiseAllArr).then(sizes => resolve(sizes))
  400. })
  401. },
  402. // 获取各个标签的尺寸
  403. queryRect(el, item) {
  404. // #ifndef APP-NVUE
  405. // $uGetRect为uView自带的节点查询简化方法,详见文档介绍:https://uview.d3u.cn/js/getRect.html
  406. // 组件内部一般用this.$uGetRect,对外的为uni.$u.getRect,二者功能一致,名称不同
  407. return new Promise(resolve => {
  408. this.$uGetRect(`.${el}`).then(size => {
  409. resolve(size)
  410. })
  411. })
  412. // #endif
  413. // #ifdef APP-NVUE
  414. // nvue下,使用dom模块查询元素高度
  415. // 返回一个promise,让调用此方法的主体能使用then回调
  416. return new Promise(resolve => {
  417. dom.getComponentRect(item ? this.$refs[el][0] : this.$refs[el], res => {
  418. resolve(res.size)
  419. })
  420. })
  421. // #endif
  422. },
  423. // 触摸开始事件
  424. onTouchStart(event) {
  425. if (!this.swipeable) return
  426. const touch = event.touches[0]
  427. this.touch.direction = ''
  428. this.touch.deltaX = 0
  429. this.touch.deltaY = 0
  430. this.touch.offsetX = 0
  431. this.touch.offsetY = 0
  432. this.touch.startX = touch.clientX
  433. this.touch.startY = touch.clientY
  434. this.dragging = true
  435. this.dragOffsetPct = 0
  436. },
  437. // 触摸移动事件
  438. onTouchMove(event) {
  439. if (!this.swipeable) return
  440. const touch = event.touches[0]
  441. this.touch.deltaX = touch.clientX - this.touch.startX
  442. this.touch.deltaY = touch.clientY - this.touch.startY
  443. this.touch.offsetX = Math.abs(this.touch.deltaX)
  444. this.touch.offsetY = Math.abs(this.touch.deltaY)
  445. this.touch.direction = this.touch.offsetX > this.touch.offsetY ? 'horizontal' : this.touch.offsetX < this.touch.offsetY ? 'vertical' : ''
  446. if (this.touch.direction === 'horizontal') {
  447. const containerWidth = this.tabsRect.width || uni.$u.window().windowWidth
  448. if (containerWidth) {
  449. this.dragOffsetPct = (this.touch.deltaX / containerWidth) * 100
  450. }
  451. }
  452. },
  453. // 触摸结束事件
  454. onTouchEnd() {
  455. if (!this.swipeable) return
  456. const minSwipeDistance = 50
  457. if (this.touch.direction === 'horizontal' && this.touch.offsetX >= minSwipeDistance) {
  458. const step = this.touch.deltaX > 0 ? -1 : 1
  459. const nextIndex = this.findAvailableByStep(this.innerCurrent, step)
  460. if (nextIndex !== -1) {
  461. this.switchToTab(nextIndex)
  462. }
  463. }
  464. this.dragging = false
  465. this.dragOffsetPct = 0
  466. },
  467. // 切换到指定标签
  468. switchToTab(index) {
  469. if (index < 0 || index >= this.computedList.length) return
  470. const targetItem = this.computedList[index]
  471. if (targetItem && !targetItem.disabled) {
  472. this.innerCurrent = index
  473. this.resize()
  474. this.$emit('change', {
  475. ...targetItem,
  476. index
  477. })
  478. this.updateChildren()
  479. } else {
  480. this.findNextAvailableTab(index)
  481. }
  482. },
  483. // 根据方向步进查找下一个可用索引
  484. findAvailableByStep(startIndex, step) {
  485. const list = this.computedList
  486. if (!Array.isArray(list) || list.length === 0) return -1
  487. let i = startIndex + step
  488. while (i >= 0 && i < list.length) {
  489. if (list[i] && !list[i].disabled) return i
  490. i += step
  491. }
  492. return -1
  493. }
  494. },
  495. }
  496. </script>
  497. <style lang="scss" scoped>
  498. @import "../../libs/css/components.scss";
  499. .u-tabs {
  500. &__wrapper {
  501. @include flex;
  502. align-items: center;
  503. &__scroll-view-wrapper {
  504. flex: 1;
  505. /* #ifndef APP-NVUE */
  506. overflow: auto hidden;
  507. /* #endif */
  508. }
  509. &__scroll-view {
  510. @include flex;
  511. flex: 1;
  512. }
  513. &__nav {
  514. @include flex;
  515. position: relative;
  516. &__item {
  517. padding: 0 11px;
  518. @include flex;
  519. align-items: center;
  520. justify-content: center;
  521. /* #ifdef H5 */
  522. cursor: pointer;
  523. /* #endif */
  524. &--disabled {
  525. /* #ifdef H5 */
  526. cursor: not-allowed;
  527. /* #endif */
  528. }
  529. &__text {
  530. font-size: 15px;
  531. color: $u-content-color;
  532. /* #ifndef APP-NVUE */
  533. white-space: nowrap;
  534. /* #endif */
  535. &--disabled {
  536. color: #ccc;
  537. }
  538. }
  539. }
  540. &__line {
  541. height: 3px;
  542. background: $u-primary;
  543. width: 30px;
  544. position: absolute;
  545. bottom: 2px;
  546. border-radius: 100px;
  547. transition-property: transform;
  548. transition-duration: 300ms;
  549. }
  550. }
  551. }
  552. &__content {
  553. overflow: hidden;
  554. &__body {
  555. position: relative;
  556. width: 100%;
  557. height: 100%;
  558. &--animated {
  559. display: flex;
  560. flex-direction: row;
  561. }
  562. }
  563. }
  564. }
  565. </style>