You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

362 lines
11 KiB

5 months ago
  1. <template>
  2. <view class="u-tabs" :class="[customClass]">
  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 list"
  21. :key="index"
  22. @tap="clickHandler(item, index)"
  23. :ref="`u-tabs__wrapper__nav__item-${index}`"
  24. :style="[addStyle(itemStyle), {flex: scrollable ? '' : 1}]"
  25. :class="[`u-tabs__wrapper__nav__item-${index}`, item.disabled && 'u-tabs__wrapper__nav__item--disabled']"
  26. >
  27. <text
  28. :class="[item.disabled && 'u-tabs__wrapper__nav__item__text--disabled']"
  29. class="u-tabs__wrapper__nav__item__text"
  30. :style="[textStyle(index)]"
  31. >{{ item[keyName] }}</text>
  32. <u-badge
  33. :show="!!(item.badge && (item.badge.show || item.badge.isDot || item.badge.value))"
  34. :isDot="item.badge && item.badge.isDot || propsBadge.isDot"
  35. :value="item.badge && item.badge.value || propsBadge.value"
  36. :max="item.badge && item.badge.max || propsBadge.max"
  37. :type="item.badge && item.badge.type || propsBadge.type"
  38. :showZero="item.badge && item.badge.showZero || propsBadge.showZero"
  39. :bgColor="item.badge && item.badge.bgColor || propsBadge.bgColor"
  40. :color="item.badge && item.badge.color || propsBadge.color"
  41. :shape="item.badge && item.badge.shape || propsBadge.shape"
  42. :numberType="item.badge && item.badge.numberType || propsBadge.numberType"
  43. :inverted="item.badge && item.badge.inverted || propsBadge.inverted"
  44. customStyle="margin-left: 4px;"
  45. ></u-badge>
  46. </view>
  47. <!-- #ifdef APP-NVUE -->
  48. <view
  49. class="u-tabs__wrapper__nav__line"
  50. ref="u-tabs__wrapper__nav__line"
  51. :style="[{
  52. width: addUnit(lineWidth),
  53. height: addUnit(lineHeight),
  54. background: lineColor,
  55. backgroundSize: lineBgSize,
  56. }]"
  57. >
  58. </view>
  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: addUnit(lineWidth),
  66. transform: `translate(${lineOffsetLeft}px)`,
  67. transitionDuration: `${firstTime ? 0 : duration}ms`,
  68. height: addUnit(lineHeight),
  69. background: lineColor,
  70. backgroundSize: lineBgSize,
  71. }]"
  72. >
  73. </view>
  74. <!-- #endif -->
  75. </view>
  76. </scroll-view>
  77. </view>
  78. <slot name="right" />
  79. </view>
  80. </view>
  81. </template>
  82. <script>
  83. // #ifdef APP-NVUE
  84. const animation = uni.requireNativePlugin('animation')
  85. const dom = uni.requireNativePlugin('dom')
  86. // #endif
  87. import { props } from './props';
  88. import { mpMixin } from '../../libs/mixin/mpMixin';
  89. import { mixin } from '../../libs/mixin/mixin';
  90. import defProps from '../../libs/config/props.js'
  91. import { addUnit, addStyle, deepMerge, getPx, sleep, sys } from '../../libs/function/index';
  92. /**
  93. * Tabs 标签
  94. * @description tabs标签组件在标签多的时候可以配置为左右滑动标签少的时候可以禁止滑动 该组件的一个特点是配置为滚动模式时激活的tab会自动移动到组件的中间位置
  95. * @tutorial https://ijry.github.io/uview-plus/components/tabs.html
  96. * @property {String | Number} duration 滑块移动一次所需的时间单位秒默认 200
  97. * @property {String | Number} swierWidth swiper的宽度默认 '750rpx'
  98. * @property {String} keyName `list`元素对象中读取的键名默认 'name'
  99. * @event {Function(index)} change 标签改变时触发 index: 点击了第几个tab索引从0开始
  100. * @event {Function(index)} click 点击标签时触发 index: 点击了第几个tab索引从0开始
  101. * @example <u-tabs :list="list" :is-scroll="false" :current="current" @change="change"></u-tabs>
  102. */
  103. export default {
  104. name: 'u-tabs',
  105. mixins: [mpMixin, mixin, props],
  106. data() {
  107. return {
  108. firstTime: true,
  109. scrollLeft: 0,
  110. scrollViewWidth: 0,
  111. lineOffsetLeft: 0,
  112. tabsRect: {
  113. left: 0
  114. },
  115. innerCurrent: 0,
  116. moving: false,
  117. }
  118. },
  119. watch: {
  120. current: {
  121. immediate: true,
  122. handler (newValue, oldValue) {
  123. // 内外部值不相等时,才尝试移动滑块
  124. if (newValue !== this.innerCurrent) {
  125. this.innerCurrent = newValue
  126. this.$nextTick(() => {
  127. this.resize()
  128. })
  129. }
  130. }
  131. },
  132. // list变化时,重新渲染list各项信息
  133. list() {
  134. this.$nextTick(() => {
  135. this.resize()
  136. })
  137. }
  138. },
  139. computed: {
  140. textStyle() {
  141. return index => {
  142. const style = {}
  143. // 取当期是否激活的样式
  144. const customeStyle = index === this.innerCurrent ? addStyle(this.activeStyle) : addStyle(this.inactiveStyle)
  145. // 如果当前菜单被禁用,则加上对应颜色,需要在此做处理,是因为nvue下,无法在style样式中通过!import覆盖标签的内联样式
  146. if (this.list[index].disabled) {
  147. style.color = '#c8c9cc'
  148. }
  149. return deepMerge(customeStyle, style)
  150. }
  151. },
  152. propsBadge() {
  153. return defProps.badge
  154. }
  155. },
  156. async mounted() {
  157. this.init()
  158. },
  159. emits: ['click', 'change'],
  160. methods: {
  161. addStyle,
  162. addUnit,
  163. setLineLeft() {
  164. const tabItem = this.list[this.innerCurrent];
  165. if (!tabItem) {
  166. return;
  167. }
  168. // 获取滑块该移动的位置
  169. let lineOffsetLeft = this.list
  170. .slice(0, this.innerCurrent)
  171. .reduce((total, curr) => total + curr.rect.width, 0);
  172. // 获取下划线的数值px表示法
  173. const lineWidth = getPx(this.lineWidth);
  174. this.lineOffsetLeft = lineOffsetLeft + (tabItem.rect.width - lineWidth) / 2
  175. // #ifdef APP-NVUE
  176. // 第一次移动滑块,无需过渡时间
  177. this.animation(this.lineOffsetLeft, this.firstTime ? 0 : parseInt(this.duration))
  178. // #endif
  179. // 如果是第一次执行此方法,让滑块在初始化时,瞬间滑动到第一个tab item的中间
  180. // 这里需要一个定时器,因为在非nvue下,是直接通过style绑定过渡时间,需要等其过渡完成后,再设置为false(非第一次移动滑块)
  181. if (this.firstTime) {
  182. setTimeout(() => {
  183. this.firstTime = false
  184. }, 10);
  185. }
  186. },
  187. // nvue下设置滑块的位置
  188. animation(x, duration = 0) {
  189. // #ifdef APP-NVUE
  190. const ref = this.$refs['u-tabs__wrapper__nav__line']
  191. animation.transition(ref, {
  192. styles: {
  193. transform: `translateX(${x}px)`
  194. },
  195. duration
  196. })
  197. // #endif
  198. },
  199. // 点击某一个标签
  200. clickHandler(item, index) {
  201. // 因为标签可能为disabled状态,所以click是一定会发出的,但是change事件是需要可用的状态才发出
  202. this.$emit('click', {
  203. ...item,
  204. index
  205. }, index)
  206. // 如果disabled状态,返回
  207. if (item.disabled) return
  208. this.innerCurrent = index
  209. this.resize()
  210. this.$emit('change', {
  211. ...item,
  212. index
  213. }, index)
  214. },
  215. init() {
  216. sleep().then(() => {
  217. this.resize()
  218. })
  219. },
  220. setScrollLeft() {
  221. // 当前活动tab的布局信息,有tab菜单的width和left(为元素左边界到父元素左边界的距离)等信息
  222. const tabRect = this.list[this.innerCurrent]
  223. // 累加得到当前item到左边的距离
  224. const offsetLeft = this.list
  225. .slice(0, this.innerCurrent)
  226. .reduce((total, curr) => {
  227. return total + curr.rect.width
  228. }, 0)
  229. // 此处为屏幕宽度
  230. const windowWidth = sys().windowWidth
  231. // 将活动的tabs-item移动到屏幕正中间,实际上是对scroll-view的移动
  232. let scrollLeft = offsetLeft - (this.tabsRect.width - tabRect.rect.width) / 2 - (windowWidth - this.tabsRect
  233. .right) / 2 + this.tabsRect.left / 2
  234. // 这里做一个限制,限制scrollLeft的最大值为整个scroll-view宽度减去tabs组件的宽度
  235. scrollLeft = Math.min(scrollLeft, this.scrollViewWidth - this.tabsRect.width)
  236. this.scrollLeft = Math.max(0, scrollLeft)
  237. },
  238. // 获取所有标签的尺寸
  239. resize() {
  240. // 如果不存在list,则不处理
  241. if(this.list.length === 0) {
  242. return
  243. }
  244. Promise.all([this.getTabsRect(), this.getAllItemRect()]).then(([tabsRect, itemRect = []]) => {
  245. this.tabsRect = tabsRect
  246. this.scrollViewWidth = 0
  247. itemRect.map((item, index) => {
  248. // 计算scroll-view的宽度,这里
  249. this.scrollViewWidth += item.width
  250. // 另外计算每一个item的中心点X轴坐标
  251. this.list[index].rect = item
  252. })
  253. // 获取了tabs的尺寸之后,设置滑块的位置
  254. this.setLineLeft()
  255. this.setScrollLeft()
  256. })
  257. },
  258. // 获取导航菜单的尺寸
  259. getTabsRect() {
  260. return new Promise(resolve => {
  261. this.queryRect('u-tabs__wrapper__scroll-view').then(size => resolve(size))
  262. })
  263. },
  264. // 获取所有标签的尺寸
  265. getAllItemRect() {
  266. return new Promise(resolve => {
  267. const promiseAllArr = this.list.map((item, index) => this.queryRect(
  268. `u-tabs__wrapper__nav__item-${index}`, true))
  269. Promise.all(promiseAllArr).then(sizes => resolve(sizes))
  270. })
  271. },
  272. // 获取各个标签的尺寸
  273. queryRect(el, item) {
  274. // #ifndef APP-NVUE
  275. // $uGetRect为uView自带的节点查询简化方法,详见文档介绍:https://ijry.github.io/uview-plus/js/getRect.html
  276. // 组件内部一般用this.$uGetRect,对外的为uni.$u.getRect,二者功能一致,名称不同
  277. return new Promise(resolve => {
  278. this.$uGetRect(`.${el}`).then(size => {
  279. resolve(size)
  280. })
  281. })
  282. // #endif
  283. // #ifdef APP-NVUE
  284. // nvue下,使用dom模块查询元素高度
  285. // 返回一个promise,让调用此方法的主体能使用then回调
  286. return new Promise(resolve => {
  287. dom.getComponentRect(item ? this.$refs[el][0] : this.$refs[el], res => {
  288. resolve(res.size)
  289. })
  290. })
  291. // #endif
  292. },
  293. },
  294. }
  295. </script>
  296. <style lang="scss" scoped>
  297. @import "../../libs/css/components.scss";
  298. .u-tabs {
  299. &__wrapper {
  300. @include flex;
  301. align-items: center;
  302. &__scroll-view-wrapper {
  303. flex: 1;
  304. /* #ifndef APP-NVUE */
  305. overflow: auto hidden;
  306. /* #endif */
  307. }
  308. &__scroll-view {
  309. @include flex;
  310. flex: 1;
  311. }
  312. &__nav {
  313. @include flex;
  314. position: relative;
  315. &__item {
  316. padding: 0 11px;
  317. @include flex;
  318. align-items: center;
  319. justify-content: center;
  320. cursor: pointer;
  321. &--disabled {
  322. /* #ifndef APP-NVUE */
  323. cursor: not-allowed;
  324. /* #endif */
  325. }
  326. &__text {
  327. font-size: 15px;
  328. color: $u-content-color;
  329. white-space: nowrap !important;
  330. &--disabled {
  331. color: $u-disabled-color !important;
  332. }
  333. }
  334. }
  335. &__line {
  336. height: 3px;
  337. background: $u-primary;
  338. width: 30px;
  339. position: absolute;
  340. bottom: 2px;
  341. border-radius: 100px;
  342. transition-property: transform;
  343. transition-duration: 300ms;
  344. }
  345. }
  346. }
  347. }
  348. </style>