u-tabs.vue 13 KB

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