u-tabs.vue 13 KB

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