u-tabs.vue 12 KB

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