su-tabs.vue 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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
  223. .createSelectorQuery()
  224. .in(this)
  225. [all ? 'selectAll' : 'select'](selector)
  226. .boundingClientRect((rect) => {
  227. if (all && Array.isArray(rect) && rect.length) {
  228. resolve(rect);
  229. }
  230. if (!all && rect) {
  231. resolve(rect);
  232. }
  233. })
  234. .exec();
  235. });
  236. },
  237. setLineLeft() {
  238. const tabItem = this.list[this.innerCurrent];
  239. if (!tabItem) {
  240. return;
  241. }
  242. // 获取滑块该移动的位置
  243. let lineOffsetLeft = this.list
  244. .slice(0, this.innerCurrent)
  245. .reduce((total, curr) => total + curr.rect.width, 0);
  246. // 获取下划线的数值px表示法
  247. const lineWidth = getPx(this.lineWidth);
  248. this.lineOffsetLeft = lineOffsetLeft + (tabItem.rect.width - lineWidth) / 2;
  249. // #ifdef APP-NVUE
  250. // 第一次移动滑块,无需过渡时间
  251. this.animation(this.lineOffsetLeft, this.firstTime ? 0 : parseInt(this.duration));
  252. // #endif
  253. // 如果是第一次执行此方法,让滑块在初始化时,瞬间滑动到第一个tab item的中间
  254. // 这里需要一个定时器,因为在非nvue下,是直接通过style绑定过渡时间,需要等其过渡完成后,再设置为false(非第一次移动滑块)
  255. if (this.firstTime) {
  256. setTimeout(() => {
  257. this.firstTime = false;
  258. }, 10);
  259. }
  260. },
  261. // nvue下设置滑块的位置
  262. animation(x, duration = 0) {
  263. // #ifdef APP-NVUE
  264. const ref = this.$refs['u-tabs__wrapper__nav__line'];
  265. animation.transition(ref, {
  266. styles: {
  267. transform: `translateX(${x}px)`,
  268. },
  269. duration,
  270. });
  271. // #endif
  272. },
  273. // 点击某一个标签
  274. clickHandler(item, index) {
  275. // 因为标签可能为disabled状态,所以click是一定会发出的,但是change事件是需要可用的状态才发出
  276. this.$emit('click', {
  277. ...item,
  278. index,
  279. });
  280. // 如果disabled状态,返回
  281. if (item.disabled) return;
  282. this.innerCurrent = index;
  283. this.resize();
  284. this.$emit('change', {
  285. ...item,
  286. index,
  287. });
  288. },
  289. init() {
  290. sleep().then(() => {
  291. this.resize();
  292. });
  293. },
  294. setScrollLeft() {
  295. // 当前活动tab的布局信息,有tab菜单的width和left(为元素左边界到父元素左边界的距离)等信息
  296. const tabRect = this.list[this.innerCurrent];
  297. // 累加得到当前item到左边的距离
  298. const offsetLeft = this.list.slice(0, this.innerCurrent).reduce((total, curr) => {
  299. return total + curr.rect.width;
  300. }, 0);
  301. // 此处为屏幕宽度
  302. const windowWidth = sys().windowWidth;
  303. // 将活动的tabs-item移动到屏幕正中间,实际上是对scroll-view的移动
  304. let scrollLeft =
  305. offsetLeft -
  306. (this.tabsRect.width - tabRect.rect.width) / 2 -
  307. (windowWidth - this.tabsRect.right) / 2 +
  308. this.tabsRect.left / 2;
  309. // 这里做一个限制,限制scrollLeft的最大值为整个scroll-view宽度减去tabs组件的宽度
  310. scrollLeft = Math.min(scrollLeft, this.scrollViewWidth - this.tabsRect.width);
  311. this.scrollLeft = Math.max(0, scrollLeft);
  312. },
  313. // 获取所有标签的尺寸
  314. resize() {
  315. // 如果不存在list,则不处理
  316. if (this.list.length === 0) {
  317. return;
  318. }
  319. Promise.all([this.getTabsRect(), this.getAllItemRect()]).then(
  320. ([tabsRect, itemRect = []]) => {
  321. this.tabsRect = tabsRect;
  322. this.scrollViewWidth = 0;
  323. itemRect.map((item, index) => {
  324. // 计算scroll-view的宽度,这里
  325. this.scrollViewWidth += item.width;
  326. // 另外计算每一个item的中心点X轴坐标
  327. this.list[index].rect = item;
  328. });
  329. // 获取了tabs的尺寸之后,设置滑块的位置
  330. this.setLineLeft();
  331. this.setScrollLeft();
  332. },
  333. );
  334. },
  335. // 获取导航菜单的尺寸
  336. getTabsRect() {
  337. return new Promise((resolve) => {
  338. this.queryRect('u-tabs__wrapper__scroll-view').then((size) => resolve(size));
  339. });
  340. },
  341. // 获取所有标签的尺寸
  342. getAllItemRect() {
  343. return new Promise((resolve) => {
  344. const promiseAllArr = this.list.map((item, index) =>
  345. this.queryRect(`u-tabs__wrapper__nav__item-${index}`, true),
  346. );
  347. Promise.all(promiseAllArr).then((sizes) => resolve(sizes));
  348. });
  349. },
  350. // 获取各个标签的尺寸
  351. queryRect(el, item) {
  352. // #ifndef APP-NVUE
  353. // $uGetRect为uView自带的节点查询简化方法,详见文档介绍:https://www.uviewui.com/js/getRect.html
  354. // 组件内部一般用this.$uGetRect,对外的为uni.$u.getRect,二者功能一致,名称不同
  355. return new Promise((resolve) => {
  356. this.$uGetRect(`.${el}`).then((size) => {
  357. resolve(size);
  358. });
  359. });
  360. // #endif
  361. // #ifdef APP-NVUE
  362. // nvue下,使用dom模块查询元素高度
  363. // 返回一个promise,让调用此方法的主体能使用then回调
  364. return new Promise((resolve) => {
  365. dom.getComponentRect(item ? this.$refs[el][0] : this.$refs[el], (res) => {
  366. resolve(res.size);
  367. });
  368. });
  369. // #endif
  370. },
  371. },
  372. };
  373. </script>
  374. <style lang="scss" scoped>
  375. .u-tabs {
  376. background: #fff;
  377. border-bottom: 2rpx solid #eee;
  378. &__wrapper {
  379. @include flex;
  380. align-items: center;
  381. &__scroll-view-wrapper {
  382. flex: 1;
  383. /* #ifndef APP-NVUE */
  384. overflow: auto hidden;
  385. /* #endif */
  386. }
  387. &__nav {
  388. @include flex;
  389. position: relative;
  390. &__item {
  391. padding: 0 11px;
  392. @include flex;
  393. align-items: center;
  394. justify-content: center;
  395. &--disabled {
  396. /* #ifndef APP-NVUE */
  397. cursor: not-allowed;
  398. /* #endif */
  399. }
  400. &__text {
  401. font-size: 14px;
  402. color: #606266;
  403. white-space: nowrap !important;
  404. &--disabled {
  405. color: #c8c9cc !important;
  406. }
  407. }
  408. }
  409. &__line {
  410. height: 3px;
  411. background: #3c9cff;
  412. width: 30px;
  413. position: absolute;
  414. bottom: 2px;
  415. border-radius: 100px;
  416. transition-property: transform;
  417. transition-duration: 300ms;
  418. }
  419. }
  420. }
  421. }
  422. </style>