cl-tabs.uvue 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. <template>
  2. <view
  3. class="cl-tabs"
  4. :class="[
  5. {
  6. 'cl-tabs--line': showLine,
  7. 'cl-tabs--slider': showSlider,
  8. 'cl-tabs--fill': fill,
  9. 'cl-tabs--disabled': disabled,
  10. 'is-dark': isDark
  11. },
  12. pt.className
  13. ]"
  14. :style="{
  15. height: parseRpx(height!)
  16. }"
  17. >
  18. <scroll-view
  19. class="cl-tabs__scrollbar"
  20. :scroll-with-animation="true"
  21. :scroll-x="true"
  22. direction="horizontal"
  23. :scroll-left="scrollLeft"
  24. :show-scrollbar="false"
  25. >
  26. <view class="cl-tabs__inner">
  27. <view
  28. class="cl-tabs__item"
  29. v-for="(item, index) in list"
  30. :key="index"
  31. :class="[pt.item?.className]"
  32. :style="{
  33. padding: `0 ${parseRpx(gutter)}`
  34. }"
  35. @tap="change(index)"
  36. >
  37. <slot name="item" :item="item" :active="item.isActive">
  38. <cl-text
  39. :pt="{
  40. className: parseClass([
  41. 'cl-tabs__item-label',
  42. {
  43. 'is-active': item.isActive,
  44. 'is-disabled': item.disabled,
  45. 'is-dark': isDark,
  46. 'is-fill': fill
  47. },
  48. pt.text?.className
  49. ])
  50. }"
  51. :style="getTextStyle(item)"
  52. >{{ item.label }}</cl-text
  53. >
  54. </slot>
  55. </view>
  56. <template v-if="lineLeft > 0">
  57. <view
  58. class="cl-tabs__line"
  59. :class="[pt.line?.className]"
  60. :style="lineStyle"
  61. v-if="showLine"
  62. ></view>
  63. <view
  64. class="cl-tabs__slider"
  65. :class="[pt.slider?.className]"
  66. :style="sliderStyle"
  67. v-if="showSlider"
  68. ></view>
  69. </template>
  70. </view>
  71. </scroll-view>
  72. </view>
  73. </template>
  74. <script lang="ts" setup>
  75. import { type PropType, computed, getCurrentInstance, nextTick, onMounted, ref, watch } from "vue";
  76. import { isDark, isEmpty, isHarmony, isNull, parseClass, parsePt, parseRpx, rpx2px } from "@/cool";
  77. import type { ClTabsItem, PassThroughProps } from "../../types";
  78. // 定义标签类型
  79. type Item = {
  80. label: string;
  81. value: string | number;
  82. disabled: boolean;
  83. isActive: boolean;
  84. };
  85. defineOptions({
  86. name: "cl-tabs"
  87. });
  88. defineSlots<{
  89. item(props: { item: Item; active: boolean }): any;
  90. }>();
  91. const props = defineProps({
  92. // 透传属性对象,允许外部自定义样式和属性
  93. pt: {
  94. type: Object,
  95. default: () => ({})
  96. },
  97. // v-model绑定值,表示当前选中的tab
  98. modelValue: {
  99. type: [String, Number] as PropType<string | number>,
  100. default: ""
  101. },
  102. // 标签高度
  103. height: {
  104. type: [String, Number] as PropType<string | number>,
  105. default: 80
  106. },
  107. // 标签列表
  108. list: {
  109. type: Array as PropType<ClTabsItem[]>,
  110. default: () => []
  111. },
  112. // 是否填充标签
  113. fill: {
  114. type: Boolean,
  115. default: false
  116. },
  117. // 标签间隔
  118. gutter: {
  119. type: Number,
  120. default: 30
  121. },
  122. // 选中标签的颜色
  123. color: {
  124. type: String,
  125. default: ""
  126. },
  127. // 未选中标签的颜色
  128. unColor: {
  129. type: String,
  130. default: ""
  131. },
  132. // 是否显示下划线
  133. showLine: {
  134. type: Boolean,
  135. default: true
  136. },
  137. // 是否显示滑块
  138. showSlider: {
  139. type: Boolean,
  140. default: false
  141. },
  142. // 是否禁用
  143. disabled: {
  144. type: Boolean,
  145. default: false
  146. }
  147. });
  148. // 定义事件发射器
  149. const emit = defineEmits(["update:modelValue", "change"]);
  150. // 获取当前组件实例的proxy对象
  151. const { proxy } = getCurrentInstance()!;
  152. // 定义透传类型,便于类型推断和扩展
  153. type PassThrough = {
  154. // 额外类名
  155. className?: string;
  156. // 文本的透传属性
  157. text?: PassThroughProps;
  158. // 单个item的透传属性
  159. item?: PassThroughProps;
  160. // 下划线的透传属性
  161. line?: PassThroughProps;
  162. // 滑块的透传属性
  163. slider?: PassThroughProps;
  164. };
  165. // 计算透传属性,便于样式和属性扩展
  166. const pt = computed(() => parsePt<PassThrough>(props.pt));
  167. // 当前选中的标签值
  168. const active = ref(props.modelValue);
  169. // 计算标签列表,增加isActive和disabled属性,便于渲染和状态判断
  170. const list = computed(() =>
  171. props.list.map((e) => {
  172. return {
  173. label: e.label,
  174. value: e.value,
  175. // 如果未传disabled则默认为false
  176. disabled: e.disabled ?? false,
  177. // 判断当前标签是否为激活状态
  178. isActive: e.value == active.value
  179. } as Item;
  180. })
  181. );
  182. // 切换标签时触发,参数为索引
  183. async function change(index: number) {
  184. // 如果整个Tabs被禁用,则不响应点击
  185. if (props.disabled) {
  186. return false;
  187. }
  188. // 获取当前点击标签的值
  189. const { value, disabled } = list.value[index];
  190. // 如果标签被禁用,则不响应点击
  191. if (disabled) {
  192. return false;
  193. }
  194. // 触发v-model的更新
  195. emit("update:modelValue", value);
  196. // 触发change事件
  197. emit("change", value);
  198. }
  199. // 获取当前选中标签的下标,未找到则返回0
  200. function getIndex() {
  201. const index = list.value.findIndex((e) => e.isActive);
  202. return index == -1 ? 0 : index;
  203. }
  204. // 根据激活状态获取标签颜色
  205. function getColor(isActive: boolean) {
  206. let color: string;
  207. // 选中时取props.color,否则取props.unColor
  208. if (isActive) {
  209. color = props.color;
  210. } else {
  211. color = props.unColor;
  212. }
  213. return isEmpty(color) ? null : color;
  214. }
  215. // tab区域宽度
  216. const tabWidth = ref(0);
  217. // tab区域左侧偏移
  218. const tabLeft = ref(0);
  219. // 下划线左侧偏移
  220. const lineLeft = ref(0);
  221. // 滑块左侧偏移
  222. const sliderLeft = ref(0);
  223. // 滑块宽度
  224. const sliderWidth = ref(0);
  225. // 滚动条左侧偏移
  226. const scrollLeft = ref(0);
  227. // 单个标签的位置信息类型,包含left和width
  228. type ItemRect = {
  229. left: number;
  230. width: number;
  231. };
  232. // 所有标签的位置信息,响应式数组
  233. const itemRects = ref<ItemRect[]>([]);
  234. // 计算下划线样式
  235. const lineStyle = computed(() => {
  236. const style = {};
  237. style["transform"] = `translateX(${lineLeft.value}px)`;
  238. // 获取选中颜色
  239. const bgColor = getColor(true);
  240. if (bgColor != null) {
  241. style["backgroundColor"] = bgColor;
  242. }
  243. return style;
  244. });
  245. // 计算滑块样式
  246. const sliderStyle = computed(() => {
  247. const style = {};
  248. style["transform"] = `translateX(${sliderLeft.value}px)`;
  249. style["width"] = sliderWidth.value + "px";
  250. // 获取选中颜色
  251. const bgColor = getColor(true);
  252. if (bgColor != null) {
  253. style["backgroundColor"] = bgColor;
  254. }
  255. return style;
  256. });
  257. // 获取文本样式
  258. function getTextStyle(item: Item) {
  259. const style = {};
  260. // 获取选中颜色
  261. const color = getColor(item.isActive);
  262. if (color != null) {
  263. style["color"] = color;
  264. }
  265. return style;
  266. }
  267. // 更新下划线、滑块、滚动条等位置
  268. function updatePosition() {
  269. nextTick(() => {
  270. if (!isEmpty(itemRects.value)) {
  271. // 获取当前选中标签的位置信息
  272. const item = itemRects.value[getIndex()];
  273. // 如果标签存在
  274. if (!isNull(item)) {
  275. // 计算滚动条偏移,使选中项居中
  276. let x = item.left - (tabWidth.value - item.width) / 2 - tabLeft.value;
  277. // 防止滚动条偏移为负
  278. if (x < 0) {
  279. x = 0;
  280. }
  281. // 设置滚动条偏移
  282. scrollLeft.value = x;
  283. // 设置下划线偏移,使下划线居中于选中项
  284. lineLeft.value = item.left + item.width / 2 - rpx2px(16) - tabLeft.value;
  285. // 设置滑块左侧偏移
  286. sliderLeft.value = item.left - tabLeft.value;
  287. // 设置滑块宽度
  288. sliderWidth.value = item.width;
  289. }
  290. }
  291. });
  292. }
  293. // 获取所有标签的位置信息,便于后续计算
  294. function getRects() {
  295. // 创建选择器查询
  296. uni.createSelectorQuery()
  297. // 作用域限定为当前组件
  298. .in(proxy)
  299. // 选择所有标签元素
  300. .selectAll(".cl-tabs__item")
  301. // 获取rect和size信息
  302. .fields({ rect: true, size: true }, () => {})
  303. // 执行查询
  304. .exec((nodes) => {
  305. // 解析查询结果,生成ItemRect数组
  306. itemRects.value = (nodes[0] as NodeInfo[]).map((e) => {
  307. return {
  308. left: e.left ?? 0,
  309. width: e.width ?? 0
  310. } as ItemRect;
  311. });
  312. // 更新下划线、滑块等位置
  313. updatePosition();
  314. });
  315. }
  316. // 刷新tab区域的宽度和位置信息
  317. function refresh() {
  318. setTimeout(
  319. () => {
  320. // 创建选择器查询
  321. uni.createSelectorQuery()
  322. // 作用域限定为当前组件
  323. .in(proxy)
  324. // 选择tab容器
  325. .select(".cl-tabs")
  326. // 获取容器的left和width
  327. .boundingClientRect((node) => {
  328. // 设置tab左侧偏移
  329. tabLeft.value = (node as NodeInfo).left ?? 0;
  330. // 设置tab宽度
  331. tabWidth.value = (node as NodeInfo).width ?? 0;
  332. // 获取所有标签的位置信息
  333. getRects();
  334. })
  335. .exec();
  336. },
  337. isHarmony() ? 50 : 0
  338. );
  339. }
  340. // 监听modelValue变化,更新active和位置
  341. watch(
  342. computed(() => props.modelValue!),
  343. (val: string | number) => {
  344. // 更新当前选中标签
  345. active.value = val;
  346. // 更新下划线、滑块等位置
  347. updatePosition();
  348. },
  349. {
  350. // 立即执行一次
  351. immediate: true
  352. }
  353. );
  354. // 监听标签列表变化,刷新布局
  355. watch(
  356. computed(() => props.list),
  357. () => {
  358. nextTick(() => {
  359. refresh();
  360. });
  361. }
  362. );
  363. // 组件挂载时刷新布局,确保初始渲染正确
  364. onMounted(() => {
  365. refresh();
  366. });
  367. </script>
  368. <style lang="scss" scoped>
  369. .cl-tabs {
  370. &__scrollbar {
  371. @apply flex flex-row w-full h-full;
  372. }
  373. &__inner {
  374. @apply flex flex-row relative;
  375. }
  376. &__item {
  377. @apply flex flex-row items-center justify-center h-full relative z-10;
  378. &-label {
  379. @apply text-surface-700 text-md;
  380. &.is-dark {
  381. @apply text-white;
  382. }
  383. &.is-active {
  384. @apply text-primary-500;
  385. }
  386. &.is-disabled {
  387. @apply text-surface-400;
  388. }
  389. }
  390. }
  391. &__line {
  392. @apply bg-primary-500 rounded-md absolute;
  393. height: 4rpx;
  394. width: 16px;
  395. bottom: 2rpx;
  396. left: 0;
  397. transition-property: transform;
  398. transition-duration: 0.3s;
  399. }
  400. &__slider {
  401. @apply bg-primary-500 rounded-lg absolute h-full w-full;
  402. top: 0;
  403. left: 0;
  404. transition-property: transform;
  405. transition-duration: 0.3s;
  406. }
  407. &--slider {
  408. @apply bg-surface-50 rounded-lg;
  409. .cl-tabs__item-label {
  410. &.is-active {
  411. @apply text-white;
  412. }
  413. }
  414. &.is-dark {
  415. @apply bg-surface-700;
  416. }
  417. }
  418. &--fill {
  419. .cl-tabs__inner {
  420. @apply w-full;
  421. }
  422. .cl-tabs__item {
  423. flex: 1;
  424. }
  425. .cl-tabs__item-label {
  426. @apply text-center;
  427. }
  428. }
  429. &--disabled {
  430. @apply opacity-50;
  431. }
  432. }
  433. </style>