first commit

This commit is contained in:
lingxiao865
2026-02-10 08:05:03 +08:00
commit c5af079d8c
1094 changed files with 97530 additions and 0 deletions

View File

@@ -0,0 +1,89 @@
:: BASE_DOC ::
## API
### Tabs Props
name | type | default | description | required
-- | -- | -- | -- | --
custom-style | Object | - | CSS(Cascading Style Sheets) | N
animation | Object | - | Typescript`TabAnimation` `type TabAnimation = { duration: number } & Record<string, any>`。[see more ts definition](https://github.com/Tencent/tdesign-miniprogram/tree/develop/packages/uniapp-components/tabs/type.ts) | N
bottom-line-mode | String | fixed | options: fixed/auto/full | N
show-bottom-line | Boolean | true | \- | N
space-evenly | Boolean | true | \- | N
split | Boolean | true | \- | N
sticky | Boolean | false | \- | N
sticky-props | Object | - | Typescript`StickyProps`[Sticky API Documents](./sticky?tab=api)。[see more ts definition](https://github.com/Tencent/tdesign-miniprogram/tree/develop/packages/uniapp-components/tabs/type.ts) | N
swipeable | Boolean | true | \- | N
theme | String | line | options: line/tag/card | N
value | String / Number | - | `v-model:value` is supported。Typescript`TabValue` `type TabValue = string \| number`。[see more ts definition](https://github.com/Tencent/tdesign-miniprogram/tree/develop/packages/uniapp-components/tabs/type.ts) | N
default-value | String / Number | - | uncontrolled property。Typescript`TabValue` `type TabValue = string \| number`。[see more ts definition](https://github.com/Tencent/tdesign-miniprogram/tree/develop/packages/uniapp-components/tabs/type.ts) | N
### Tabs Events
name | params | description
-- | -- | --
change | `(context: { value: TabValue; label: string })` | \-
click | `(context: { value: TabValue; label: string })` | \-
scroll | `(context: { scrollTop: number, isFixed: boolean })` | \-
### Tabs Slots
name | Description
-- | --
\- | \-
middle | \-
### Tabs External Classes
className | Description
-- | --
t-class | \-
t-class-active | \-
t-class-content | \-
t-class-item | \-
t-class-track | \-
### TabPanel Props
name | type | default | description | required
-- | -- | -- | -- | --
custom-style | Object | - | CSS(Cascading Style Sheets) | N
badge-props | Object | {} | \- | N
disabled | Boolean | false | \- | N
icon | String / Object | - | \- | N
label | String | - | \- | N
lazy | Boolean | false | Enable tab lazy loading | N
panel | String | - | \- | N
value | String / Number | - | Typescript`TabValue`[Tabs API Documents](./tabs?tab=api)。[see more ts definition](https://github.com/Tencent/tdesign-miniprogram/tree/develop/packages/uniapp-components/tab-panel/type.ts) | N
### TabPanel Slots
name | Description
-- | --
\- | \-
panel | \-
### CSS Variables
The component provides the following CSS variables, which can be used to customize styles.
Name | Default Value | Description
-- | -- | --
--td-tab-border-color | @component-stroke | -
--td-tab-font | @font-body-medium | -
--td-tab-icon-size | 36rpx | -
--td-tab-item-active-color | @brand-color | -
--td-tab-item-color | @text-color-primary | -
--td-tab-item-disabled-color | @text-color-disabled | -
--td-tab-item-height | 96rpx | -
--td-tab-item-tag-active-bg | @brand-color-light | -
--td-tab-item-tag-bg | @bg-color-secondarycontainer | -
--td-tab-item-tag-height | 64rpx | -
--td-tab-item-vertical-height | 108rpx | -
--td-tab-item-vertical-width | 208rpx | -
--td-tab-nav-bg-color | @bg-color-container | -
--td-tab-track-color | @brand-color | -
--td-tab-track-radius | 8rpx | -
--td-tab-track-thickness | 6rpx | -
--td-tab-track-width | 32rpx | -

View File

@@ -0,0 +1,198 @@
---
title: Tabs 选项卡
description: 用于内容分类后的展示切换。
spline: navigation
isComponent: true
---
## 引入
可在 `main.ts` 或在需要使用的页面或组件中引入。
```js
import TTabs from '@tdesign/uniapp/tabs/tabs.vue';
import TTabsPanel from '@tdesign/uniapp/tab-panel/tab-panel.vue';
```
### 基础选项卡
{{ base }}
### 等距选项卡
{{ scroll }}
### 带图标选项卡
{{ with-icon }}
### 带徽章选项卡
{{ with-badge }}
### 带内容区选项卡
{{ with-content }}
### 选项卡状态
{{ status }}
### 选项卡尺寸
{{ size }}
### 选项卡样式
使用 theme 属性可以变换风格,支持 line = 线条默认tag = 标签card = 卡片
{{ theme }}
<!-- 横向选项卡支持超过屏幕滑动 -->
### 受控用法
```html
<t-tabs :value="value" @change="onTabsChange">
<t-tab-panel label="标签页一" value="0">标签一内容</t-tab-panel>
<t-tab-panel label="标签页二" value="1">标签二内容</t-tab-panel>
</t-tabs>
```
```js
export default{
data: {
return {
value: '0',
};
},
methods: {
onTabsChange(e) {
this.value = e.value;
},
}
};
```
### 与 Popup 使用
```html
<t-popup :visible="visible" @visible-change="onVisibleChange">
<t-tabs ref="tabs" defaultValue="0" @change="onTabsChange" @click="onTabsClick" t-class="custom-tabs">
<t-tab-panel label="标签页一" value="0">标签一内容</t-tab-panel>
<t-tab-panel label="标签页二" value="1">标签二内容</t-tab-panel>
<t-tab-panel label="标签页三" value="2">标签三内容</t-tab-panel>
</t-tabs>
</t-popup>
```
```js
export default {
data: {
return {
visible: false,
};
},
methods: {
showPopup() {
this.visible = true;
setTimeout(() => {
const tabs = this.$refs['tabs'];
// 这一步很重要,因为小程序的无法正确执行生命周期,所以需要手动设置下 tabs 的滑块
tabs.setTrack();
});
},
},
})
```
## API
### Tabs Props
名称 | 类型 | 默认值 | 描述 | 必传
-- | -- | -- | -- | --
custom-style | Object | - | 自定义样式 | N
animation | Object | - | 动画效果设置。其中 duration 表示动画时长。单位。TS 类型:`TabAnimation` `type TabAnimation = { duration: number } & Record<string, any>`。[详细类型定义](https://github.com/Tencent/tdesign-miniprogram/tree/develop/packages/uniapp-components/tabs/type.ts) | N
bottom-line-mode | String | fixed | 激活下划线的模式。可选项fixed/auto/full | N
show-bottom-line | Boolean | true | 是否展示底部激活线条 | N
space-evenly | Boolean | true | 选项卡头部空间是否均分 | N
split | Boolean | true | `1.1.10`。是否展示分割线 | N
sticky | Boolean | false | 是否开启粘性布局 | N
sticky-props | Object | - | 透传至 Sticky 组件。TS 类型:`StickyProps`[Sticky API Documents](./sticky?tab=api)。[详细类型定义](https://github.com/Tencent/tdesign-miniprogram/tree/develop/packages/uniapp-components/tabs/type.ts) | N
swipeable | Boolean | true | 是否可以滑动切换 | N
theme | String | line | 标签的样式。可选项line/tag/card | N
value | String / Number | - | 激活的选项卡值。支持语法糖 `v-model:value`。TS 类型:`TabValue` `type TabValue = string \| number`。[详细类型定义](https://github.com/Tencent/tdesign-miniprogram/tree/develop/packages/uniapp-components/tabs/type.ts) | N
default-value | String / Number | - | 激活的选项卡值。非受控属性。TS 类型:`TabValue` `type TabValue = string \| number`。[详细类型定义](https://github.com/Tencent/tdesign-miniprogram/tree/develop/packages/uniapp-components/tabs/type.ts) | N
### Tabs Events
名称 | 参数 | 描述
-- | -- | --
change | `(context: { value: TabValue; label: string })` | 激活的选项卡发生变化时触发
click | `(context: { value: TabValue; label: string })` | 点击选项卡时触发
scroll | `(context: { scrollTop: number, isFixed: boolean })` | 页面滚动时触发
### Tabs Slots
名称 | 描述
-- | --
\- | 默认插槽,自定义选项卡内容
middle | 中间内容,介于头部和内容之间
### Tabs External Classes
类名 | 描述
-- | --
t-class | 根节点样式类
t-class-active | 激活态样式类
t-class-content | 内容样式类
t-class-item | 选项样式类
t-class-track | 滚动条样式类
### TabPanel Props
名称 | 类型 | 默认值 | 描述 | 必传
-- | -- | -- | -- | --
custom-style | Object | - | 自定义样式 | N
badge-props | Object | {} | 透传至 Badge 组件 | N
disabled | Boolean | false | 是否禁用当前选项卡 | N
icon | String / Object | - | `1.0.0-rc.1`。图标,传对象则透传至 Icon | N
label | String | - | 选项卡名称 | N
lazy | Boolean | false | 是否启用选项卡懒加载 | N
panel | String | - | 用于自定义选项卡面板内容 | N
value | String / Number | - | 选项卡的值唯一标识。TS 类型:`TabValue`[Tabs API Documents](./tabs?tab=api)。[详细类型定义](https://github.com/Tencent/tdesign-miniprogram/tree/develop/packages/uniapp-components/tab-panel/type.ts) | N
### TabPanel Slots
名称 | 描述
-- | --
\- | 默认插槽,自定义选项卡面板内容
panel | 自定义 `panel` 显示内容
### CSS Variables
组件提供了下列 CSS 变量,可用于自定义样式。
名称 | 默认值 | 描述
-- | -- | --
--td-tab-border-color | @component-stroke | -
--td-tab-font | @font-body-medium | -
--td-tab-icon-size | 36rpx | -
--td-tab-item-active-color | @brand-color | -
--td-tab-item-color | @text-color-primary | -
--td-tab-item-disabled-color | @text-color-disabled | -
--td-tab-item-height | 96rpx | -
--td-tab-item-tag-active-bg | @brand-color-light | -
--td-tab-item-tag-bg | @bg-color-secondarycontainer | -
--td-tab-item-tag-height | 64rpx | -
--td-tab-item-vertical-height | 108rpx | -
--td-tab-item-vertical-width | 208rpx | -
--td-tab-nav-bg-color | @bg-color-container | -
--td-tab-track-color | @brand-color | -
--td-tab-track-radius | 8rpx | -
--td-tab-track-thickness | 6rpx | -
--td-tab-track-width | 32rpx | -

View File

@@ -0,0 +1,26 @@
import utils from '../common/utils.wxs';
export function animate(options) {
if (options.duration) {
return utils._style({
'transition-duration': `${options.duration}s`,
transform: `translate3d( ${-100 * options.currentIndex}%,0, 0)`,
});
}
return '';
}
export function trackStyle(options) {
if (options.distance || options.lineWidth) {
return utils._style({
'-webkit-transform': `translateX(${options.distance}px)`,
transform: `translateX(${options.distance}px)`,
'transition-duration': options.isInit ? '0' : '0.3s',
width: `${options.lineWidth}px`,
opacity: 1,
});
}
return '';
}

View File

@@ -0,0 +1,80 @@
/* eslint-disable */
/**
* 该文件为脚本自动生成文件,请勿随意修改。如需修改请联系 PMC
* */
import type { TdTabsProps } from './type';
export default {
/** 动画效果设置。其中 duration 表示动画时长。(单位:秒) */
animation: {
type: Object,
},
/** 激活下划线的模式 */
bottomLineMode: {
type: String,
default: 'fixed' as TdTabsProps['bottomLineMode'],
validator(val: TdTabsProps['bottomLineMode']): boolean {
if (!val) return true;
return ['fixed', 'auto', 'full'].includes(val);
},
},
/** 是否展示底部激活线条 */
showBottomLine: {
type: Boolean,
default: true,
},
/** 选项卡头部空间是否均分 */
spaceEvenly: {
type: Boolean,
default: true,
},
/** `1.1.10`。是否展示分割线 */
split: {
type: Boolean,
default: true,
},
/** 是否开启粘性布局 */
sticky: Boolean,
/** 透传至 Sticky 组件 */
stickyProps: {
type: Object,
},
/** 是否可以滑动切换 */
swipeable: {
type: Boolean,
default: true,
},
/** 标签的样式 */
theme: {
type: String,
default: 'line' as TdTabsProps['theme'],
validator(val: TdTabsProps['theme']): boolean {
if (!val) return true;
return ['line', 'tag', 'card'].includes(val);
},
},
/** 激活的选项卡值 */
value: {
type: [String, Number],
},
/** 激活的选项卡值,非受控属性 */
defaultValue: {
type: [String, Number],
},
/** 激活的选项卡发生变化时触发 */
onChange: {
type: Function,
default: () => ({}),
},
/** 点击选项卡时触发 */
onClick: {
type: Function,
default: () => ({}),
},
/** 页面滚动时触发 */
onScroll: {
type: Function,
default: () => ({}),
},
};

View File

@@ -0,0 +1,183 @@
.t-tabs {
position: relative;
font: var(--td-tab-font, var(--td-font-body-medium, 28rpx / 44rpx var(--td-font-family, PingFang SC, Microsoft YaHei, Arial Regular)));
background: var(--td-tab-nav-bg-color, var(--td-bg-color-container, var(--td-font-white-1, #ffffff)));
flex-wrap: wrap;
}
.t-tabs__wrapper {
display: flex;
overflow: hidden;
background: var(--td-tab-nav-bg-color, var(--td-bg-color-container, var(--td-font-white-1, #ffffff)));
}
.t-tabs__wrapper--card {
background: var(--td-tab-item-tag-bg, var(--td-bg-color-secondarycontainer, var(--td-gray-color-1, #f3f3f3)));
--td-tab-border-color: transparent;
}
.t-tabs__item {
position: relative;
display: flex;
flex: none;
align-items: center;
justify-content: center;
font-weight: 400;
color: var(--td-tab-item-color, var(--td-text-color-primary, var(--td-font-gray-1, rgba(0, 0, 0, 0.9))));
padding: 0 var(--td-spacer-2, 32rpx);
box-sizing: border-box;
white-space: nowrap;
overflow: hidden;
height: var(--td-tab-item-height, 96rpx);
}
.t-tabs__item--active {
font-weight: 600;
color: var(--td-tab-item-active-color, var(--td-brand-color, var(--td-primary-color-7, #0052d9)));
}
.t-tabs__item--disabled {
color: var(--td-tab-item-disabled-color, var(--td-text-color-disabled, var(--td-font-gray-4, rgba(0, 0, 0, 0.26))));
}
.t-tabs__item--evenly {
flex: 1 0 auto;
}
.t-tabs__item-inner {
display: flex;
align-items: center;
justify-content: center;
}
.t-tabs__item-inner--tag {
width: 100%;
text-align: center;
padding: 0 var(--td-spacer-2, 32rpx);
line-height: var(--td-tab-item-tag-height, 64rpx);
border-radius: calc(var(--td-tab-item-tag-height, 64rpx) / 2);
background-color: var(--td-tab-item-tag-bg, var(--td-bg-color-secondarycontainer, var(--td-gray-color-1, #f3f3f3)));
}
.t-tabs__item-inner--active.t-tabs__item-inner--tag {
background-color: var(--td-tab-item-tag-active-bg, var(--td-brand-color-light, var(--td-primary-color-1, #f2f3ff)));
}
.t-tabs__item--tag:not(.t-tabs__item--evenly) {
padding: 0 calc(var(--td-spacer, 16rpx) / 2);
}
.t-tabs__item--tag:not(.t-tabs__item--evenly):first-child {
margin-left: var(--td-spacer, 16rpx);
}
.t-tabs__item--tag:not(.t-tabs__item--evenly):last-child {
padding-right: var(--td-spacer-1, 24rpx);
}
.t-tabs__item--tag {
padding: 0 var(--td-spacer, 16rpx);
}
.t-tabs__item--card.t-tabs__item--active {
background-color: var(--td-tab-nav-bg-color, var(--td-bg-color-container, var(--td-font-white-1, #ffffff)));
border-radius: var(--td-radius-large, 18rpx) var(--td-radius-large, 18rpx) 0 0;
}
.t-tabs__item--card.t-tabs__item--active:first-child {
border-top-left-radius: 0;
}
.t-tabs__item--card.t-tabs__item--active:last-child {
border-top-right-radius: 0;
}
.t-tabs__item--card.t-tabs__item--pre {
border-bottom-right-radius: var(--td-radius-large, 18rpx);
}
.t-tabs__item-prefix,
.t-tabs__item-suffix {
position: absolute;
bottom: 0;
width: 18rpx;
height: 18rpx;
background-color: var(--td-tab-nav-bg-color, var(--td-bg-color-container, var(--td-font-white-1, #ffffff)));
}
.t-tabs__item-prefix::after,
.t-tabs__item-suffix::after {
content: '';
display: block;
width: 100%;
height: 100%;
background-color: var(--td-tab-item-tag-bg, var(--td-bg-color-secondarycontainer, var(--td-gray-color-1, #f3f3f3)));
}
.t-tabs__item-prefix {
right: 0;
}
.t-tabs__item-prefix::after {
border-bottom-right-radius: var(--td-radius-large, 18rpx);
}
.t-tabs__item-suffix {
left: 0;
}
.t-tabs__item-suffix::after {
border-bottom-left-radius: var(--td-radius-large, 18rpx);
}
.t-tabs__badge--active {
--td-badge-content-text-color: var(--td-tab-item-active-color, var(--td-brand-color, var(--td-primary-color-7, #0052d9)));
}
.t-tabs__badge--disabled {
--td-badge-content-text-color: var(--td-tab-item-disabled-color, var(--td-text-color-disabled, var(--td-font-gray-4, rgba(0, 0, 0, 0.26))));
}
.t-tabs__icon {
font-size: var(--td-tab-icon-size, 36rpx);
margin-right: calc(var(--td-spacer, 16rpx) / 4);
}
.t-tabs__content {
overflow: hidden;
}
.t-tabs__nav {
position: relative;
user-select: none;
display: flex;
flex-wrap: nowrap;
align-items: center;
}
.t-tabs__nav.t-tabs__nav--evenly {
width: 100%;
}
.t-tabs__track {
position: absolute;
font-weight: 600;
z-index: 1;
opacity: 0;
background-color: var(--td-tab-track-color, var(--td-brand-color, var(--td-primary-color-7, #0052d9)));
left: 0;
bottom: 1rpx;
width: var(--td-tab-track-width, 32rpx);
height: var(--td-tab-track-thickness, 6rpx);
border-radius: var(--td-tab-track-radius, 8rpx);
}
.t-tabs__scroll {
position: relative;
height: var(--td-tab-item-height, 96rpx);
}
.t-tabs__scroll--split {
position: relative;
}
.t-tabs__scroll--split::after {
content: '';
display: block;
position: absolute;
top: unset;
bottom: 0;
left: unset;
right: unset;
background-color: var(--td-tab-border-color, var(--td-component-stroke, var(--td-gray-color-3, #e7e7e7)));
}
.t-tabs__scroll--split::after {
height: 1px;
left: 0;
right: 0;
transform: scaleY(0.5);
}
.t-tabs__scroll::-webkit-scrollbar {
display: none;
}
.t-tabs__content {
width: 100%;
}
.t-tabs__content-inner {
display: block;
}
.t-tabs__content--animated .t-tabs__content-inner {
position: relative;
width: 100%;
height: 100%;
display: flex;
will-change: left;
transition-property: transform;
}

View File

@@ -0,0 +1,494 @@
<template>
<view
:style="tools._style([customStyle])"
:class="tools.cls(classPrefix, [placement]) + ' ' + tClass"
>
<t-sticky
:t-class="tools.cls(classPrefix + '__sticky', [placement])"
:disabled="!sticky"
:z-index="(stickyProps && stickyProps.zIndex) || 1"
:offset-top="(stickyProps && stickyProps.offsetTop) || 0"
:container="stickyProps && stickyProps.container"
@scroll="onTouchScroll"
>
<view :class="tools.cls(classPrefix + '__wrapper', [theme])">
<scroll-view
:class="tools.cls(classPrefix + '__scroll', [placement, ['split', split]])"
enhanced
enable-flex
:scroll-left="offset"
:scroll-x="true"
scroll-anchoring
scroll-with-animation
enable-passive
:show-scrollbar="false"
type="list"
@scroll="onScroll"
>
<view
:class="tools.cls(classPrefix + '__nav', [placement, ['evenly', spaceEvenly]])"
aria-role="tablist"
>
<view
v-for="(item, index) in tabs"
:key="index"
:data-index="index"
:class="
tools.cls(classPrefix + '__item', [theme, ['evenly', spaceEvenly], placement, ['disabled', item.disabled], ['active', currentIndex === index]]) +
' ' +
(currentIndex === index ? tClassActive : '') +
' ' +
tClassItem
"
aria-role="tab"
:aria-controls="tabID + '_panel_' + index"
:aria-selected="currentIndex === index"
:aria-disabled="item.disabled"
:aria-label="ariaLabel || (item.badgeProps.dot || item.badgeProps.count ? item.label + tools.getBadgeAriaLabel({ ...item.badgeProps }) : '')"
@click="onTabTap"
>
<view
:class="tools.cls(classPrefix + '__item-inner', [theme, ['active', currentIndex === index]])"
:aria-hidden="item.badgeProps.dot || item.badgeProps.count"
>
<block
v-if="item.icon"
name="icon"
>
<t-icon
:t-class="classPrefix + '__icon'"
:custom-style="getIconCustomStyle(item)"
:prefix="item.icon.prefix"
:name="item.icon.name"
:size="item.icon.size"
:color="item.icon.color"
:aria-hidden="!!item.icon.ariaHidden"
:aria-label="item.icon.ariaLabel"
:aria-role="item.icon.ariaRole"
@click="item.icon.click || ''"
/>
</block>
<block v-if="item.badgeProps">
<t-badge
:color="item.badgeProps.color || ''"
:content="item.label"
:count="item.badgeProps.count || 0"
:dot="item.badgeProps.dot || false"
:max-count="item.badgeProps.maxCount || 99"
:offset="item.badgeProps.offset || []"
:shape="item.badgeProps.shape || 'circle'"
:show-zero="item.badgeProps.showZero || false"
:size="item.badgeProps.size || 'medium'"
:t-class="
tools.cls(classPrefix + '__badge', [
['disabled', item.disabled],
['active', currentIndex === index]
])
"
:custom-style="getBadgeCustomStyle(item, index)"
:t-class-content="item.badgeProps.tClassContent"
:t-class-count="item.badgeProps.tClassCount"
/>
</block>
<block v-else>
{{ item.label }}
</block>
</view>
<view
v-if="theme == 'card' && currentIndex - 1 == index"
:class="classPrefix + '__item-prefix'"
/>
<view
v-if="theme == 'card' && currentIndex + 1 == index"
:class="classPrefix + '__item-suffix'"
/>
</view>
<view
v-if="theme == 'line' && showBottomLine"
:class="tools.cls(classPrefix + '__track', [placement]) + ' ' + tClassTrack"
:style="trackStyle(trackOption)"
/>
</view>
</scroll-view>
</view>
</t-sticky>
<slot name="middle" />
<view
:class="tools.cls(classPrefix + '__content', [['animated', animation]])"
@touchstart="onTouchStart"
@touchmove="onTouchMove"
@touchend="onTouchEnd"
@touchcancel="onTouchEnd"
>
<view
:class="classPrefix + '__content-inner ' + tClassContent"
:style="animate({ duration: animation && animation.duration, currentIndex: currentIndex })"
>
<slot />
</view>
</view>
</view>
</template>
<script>
import TSticky from '../sticky/sticky';
import TBadge from '../badge/badge';
import TIcon from '../icon/icon';
import { uniComponent } from '../common/src/index';
import props from './props';
import { prefix } from '../common/config';
import touch from '../mixins/touch';
import { getRect, uniqueFactory, coalesce, nextTick } from '../common/utils';
import { getObserver } from '../common/wechat';
import tools from '../common/utils.wxs';
import { ParentMixin, RELATION_MAP } from '../common/relation';
import { animate, trackStyle } from './computed';
const name = `${prefix}-tabs`;
const getUniqueID = uniqueFactory('tabs');
export default uniComponent({
name,
options: {
styleIsolation: 'shared',
},
controlledProps: [{
key: 'value',
event: 'change',
}],
externalClasses: [
`${prefix}-class`,
`${prefix}-class-item`,
`${prefix}-class-active`,
`${prefix}-class-track`,
`${prefix}-class-content`,
],
mixins: [touch, ParentMixin(RELATION_MAP.TabPanel)],
components: {
TSticky,
TBadge,
TIcon,
},
props: {
...props,
},
emits: [
'change',
'scroll',
'error',
'click',
],
watch: {
value: {
handler(e) {
this.dataValue = e;
},
immediate: true,
},
dataValue(name) {
if (name !== this.getCurrentName()) {
this.setCurrentIndexByName(name);
}
},
},
created() {
this.children = this.children || [];
},
mounted() {
nextTick().then(() => {
this.setTrack();
});
getRect(this, `.${name}`).then((rect) => {
this.containerWidth = rect.width;
});
this.tabID = getUniqueID();
},
data() {
return {
prefix,
classPrefix: name,
tabs: [],
currentLabels: [],
currentIndex: -1,
trackOption: {
lineWidth: 0,
distance: 0,
isInit: true,
},
offset: 0,
scrollLeft: 0,
tabID: '',
placement: 'top',
tools,
dataValue: coalesce(this.value, this.defaultValue),
};
},
methods: {
trackStyle,
animate,
innerAfterLinked(target) {
// mixin 中已注入
// this.children.push(target);
this.initChildId();
target.dataIndex = this.children.length - 1;
this.updateTabs();
},
innerAfterUnlinked(target) {
this.children = this.children.filter(item => item.index !== target.dataIndex);
this.updateTabs(() => this.setTrack());
this.initChildId();
},
initChildId() {
this.children.forEach((item, index) => {
item.setId(`${this.tabID}_panel_${index}`);
});
},
onScroll(e = {}) {
const { scrollLeft } = e.detail || {};
this.scrollLeft = scrollLeft;
},
updateTabs(cb) {
const { children } = this;
const tabs = children.map((child) => {
const { label, badgeProps, disabled, icon, panel, value, lazy } = child;
return {
label, badgeProps, disabled, icon, panel, value, lazy,
};
});
tabs.forEach((item) => {
if (typeof item.icon === 'string') {
item.icon = { name: item.icon };
}
});
this.tabs = tabs;
if (typeof cb === 'function') {
setTimeout(cb, 33);
}
this.setCurrentIndexByName(this.dataValue);
},
setCurrentIndexByName(name) {
const { children } = this;
const index = children.findIndex(child => child.getComputedName() === `${name}`);
if (index > -1) {
this.setCurrentIndex(index);
}
},
setCurrentIndex(index) {
if (index <= -1 || index >= this.children.length) return;
const Labels = [];
this.children.forEach((child, idx) => {
const isActive = index === idx;
if (isActive !== child.active || !child.initialized) {
child.render(isActive, this);
}
Labels.push(child.label);
});
const { currentIndex, currentLabels } = this;
if (currentIndex === index && currentLabels.join('') === Labels.join('')) return;
this.currentIndex = index;
this.currentLabels = Labels;
setTimeout(() => {
this.setTrack();
}, 33);
},
getCurrentName() {
if (this.children) {
const activeTab = this.children[this.currentIndex];
if (activeTab) {
return activeTab.getComputedName();
}
}
},
calcScrollOffset(containerWidth, targetLeft, targetWidth, offset) {
return offset + targetLeft - (1 / 2) * containerWidth + targetWidth / 2;
},
// 外部无法获取虚拟组件节点位置信息
getTabHeight() {
return getRect(this, `.${name}`);
},
getTrackSize() {
const { bottomLineMode } = this;
const targetMap = {
fixed: `.${prefix}-tabs__track`,
auto: `.${prefix}-tabs__item--active .${prefix}-tabs__item-inner`,
full: `.${prefix}-tabs__item--active`,
};
return new Promise((resolve, reject) => {
if (this.trackWidth) {
resolve(this.trackWidth);
return;
}
getRect(this, targetMap[bottomLineMode] || targetMap.fixed)
.then((res) => {
if (res) {
resolve(res.width);
}
})
.catch(reject);
});
},
async setTrack() {
const { children } = this;
if (!children) return;
const { currentIndex } = this;
if (currentIndex <= -1) return;
try {
const res = await getRect(this, `.${prefix}-tabs__item`, true);
const rect = res[currentIndex];
if (!rect) return;
let count = 0;
let distance = 0;
let totalSize = 0;
res.forEach((item) => {
if (count < currentIndex) {
distance += item.width;
count += 1;
}
totalSize += item.width;
});
if (this.containerWidth) {
const offset = this.calcScrollOffset(this.containerWidth, rect.left, rect.width, this.scrollLeft);
const maxOffset = totalSize - this.containerWidth;
this.offset = Math.min(Math.max(offset, 0), maxOffset);
} else if (!this._hasObserved) {
this._hasObserved = true;
getObserver(this, `.${name}`).then(() => this.setTrack());
}
const lineWidth = await this.getTrackSize();
if (this.theme === 'line') {
distance += (rect.width - lineWidth) / 2;
}
const isInit = this.previousIndex === undefined;
if (isInit
|| this.previousIndex !== currentIndex
|| this.lastDistance !== distance
) {
this.previousIndex = currentIndex;
this.trackOption = { lineWidth, distance, isInit };
this.lastDistance = distance;
}
} catch (err) {
this.$emit('error', err);
}
},
onTabTap(event) {
const { index } = event.currentTarget.dataset;
this.changeIndex(index);
},
onTouchStart(event) {
if (!this.swipeable) return;
this.touchStart(event);
},
onTouchMove(event) {
if (!this.swipeable) return;
this.touchMove(event);
},
onTouchEnd() {
if (!this.swipeable) return;
const { direction, deltaX, offsetX } = this;
const minSwipeDistance = 50;
if (direction === 'horizontal' && offsetX >= minSwipeDistance) {
const index = this.getAvailableTabIndex(deltaX);
if (index !== -1) {
this.changeIndex(index);
}
}
},
onTouchScroll(event) {
this._trigger('scroll', event);
},
changeIndex(index) {
const currentTab = this.tabs[index];
const { value, label } = currentTab;
if (!currentTab?.disabled && index !== this.currentIndex) {
this._trigger('change', { value, label });
}
this._trigger('click', { value, label });
},
getAvailableTabIndex(deltaX) {
const step = deltaX > 0 ? -1 : 1;
const { currentIndex, tabs } = this;
const len = tabs.length;
for (let i = step; currentIndex + step >= 0 && currentIndex + step < len; i += step) {
const newIndex = currentIndex + i;
if (newIndex >= 0 && newIndex < len && tabs[newIndex]) {
if (!tabs[newIndex].disabled) {
return newIndex;
}
} else {
return currentIndex;
}
}
return -1;
},
getBadgeCustomStyle(item, index) {
if (item.disabled) {
return '--td-badge-content-text-color: var(--td-tab-item-disabled-color, var(--td-text-color-disabled, var(--td-font-gray-4, rgba(0, 0, 0, .26))))';
}
if (this.currentIndex === index) {
return '--td-badge-content-text-color: var(--td-tab-item-active-color, var(--td-brand-color, var(--td-primary-color-7, #0052d9)));';
}
return '';
},
getIconCustomStyle(item) {
return tools._style([
{
fontSize: 'var(--td-tab-icon-size, 18px)',
marginRight: 'calc(var(--td-spacer, 8px) / 4)',
},
item.icon.style || '',
]);
},
},
});
</script>
<style scoped>
@import './tabs.css';
/* #ifndef MP-WEIXIN */
:deep(t-tab-panel) {
flex-shrink: 0;
width: 100%;
height: 100%;
box-sizing: border-box;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
}
/* #endif */
</style>

View File

@@ -0,0 +1,77 @@
/* eslint-disable */
/**
* 该文件为脚本自动生成文件,请勿随意修改。如需修改请联系 PMC
* */
import type { TdStickyProps as StickyProps } from '../sticky/type';
export interface TdTabsProps {
/**
* 动画效果设置。其中 duration 表示动画时长。(单位:秒)
*/
animation?: TabAnimation;
/**
* 激活下划线的模式
* @default fixed
*/
bottomLineMode?: 'fixed' | 'auto' | 'full';
/**
* 是否展示底部激活线条
* @default true
*/
showBottomLine?: boolean;
/**
* 选项卡头部空间是否均分
* @default true
*/
spaceEvenly?: boolean;
/**
* `1.1.10`。是否展示分割线
* @default true
*/
split?: boolean;
/**
* 是否开启粘性布局
* @default false
*/
sticky?: boolean;
/**
* 透传至 Sticky 组件
*/
stickyProps?: StickyProps;
/**
* 是否可以滑动切换
* @default true
*/
swipeable?: boolean;
/**
* 标签的样式
* @default line
*/
theme?: 'line' | 'tag' | 'card';
/**
* 激活的选项卡值
*/
value?: TabValue;
/**
* 激活的选项卡值,非受控属性
*/
defaultValue?: TabValue;
/**
* 激活的选项卡发生变化时触发
*/
onChange?: (context: { value: TabValue; label: string }) => void;
/**
* 点击选项卡时触发
*/
onClick?: (context: { value: TabValue; label: string }) => void;
/**
* 页面滚动时触发
*/
onScroll?: (context: { scrollTop: number; isFixed: boolean }) => void;
}
export type TabAnimation = { duration: number } & Record<string, any>;
export type TabValue = string | number;