su-tabs.vue 13 KB

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