u-tabs.vue 11 KB

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