cl-tabs.uvue 9.4 KB

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