su-tabs.vue 14 KB

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