uv-tabs.vue 13 KB

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