u-tabs.vue 12 KB

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