u-tabs.vue 11 KB

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