1
0

u-tabs.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. <template>
  2. <view class="u-tabs" :style="{
  3. background: bgColor
  4. }">
  5. <!-- $u.getRect()对组件根节点无效,因为写了.in(this),故这里获取内层接点尺寸 -->
  6. <view :id="id">
  7. <scroll-view scroll-x class="u-scroll-view" :scroll-left="scrollLeft" scroll-with-animation>
  8. <view class="u-scroll-box" :id="id" :class="{'u-tabs-scroll-flex': !isScroll}">
  9. <view class="u-tab-item u-line-1" :id="'u-tab-item-' + index" v-for="(item, index) in list" :key="index" @tap="clickTab(index)"
  10. :style="[tabItemStyle(index)]">
  11. <u-badge :count="item[count] || item['count'] || 0" :offset="offset" size="mini"></u-badge>
  12. {{ item[name] || item['name']}}
  13. </view>
  14. <view v-if="showBar" class="u-tab-bar" :style="[tabBarStyle]"></view>
  15. </view>
  16. </scroll-view>
  17. </view>
  18. </view>
  19. </template>
  20. <script>
  21. /**
  22. * tabs 标签
  23. * @description 该组件,是一个tabs标签组件,在标签多的时候,可以配置为左右滑动,标签少的时候,可以禁止滑动。 该组件的一个特点是配置为滚动模式时,激活的tab会自动移动到组件的中间位置。
  24. * @tutorial https://www.uviewui.com/components/tabs.html
  25. * @property {Boolean} is-scroll tabs是否可以左右拖动(默认true)
  26. * @property {Array} list 标签数组,元素为对象,如[{name: '推荐'}]
  27. * @property {String Number} current 指定哪个tab为激活状态(默认0)
  28. * @property {String Number} height 导航栏的高度,单位rpx(默认80)
  29. * @property {String Number} font-size tab文字大小,单位rpx(默认30)
  30. * @property {String Number} duration 滑块移动一次所需的时间,单位秒(默认0.5)
  31. * @property {String} active-color 滑块和激活tab文字的颜色(默认#2979ff)
  32. * @property {String} inactive-color tabs文字颜色(默认#303133)
  33. * @property {String Number} bar-width 滑块宽度,单位rpx(默认40)
  34. * @property {Object} active-item-style 活动tabs item的样式,对象形式
  35. * @property {Object} bar-style 底部滑块的样式,对象形式
  36. * @property {Boolean} show-bar 是否显示底部的滑块(默认true)
  37. * @property {String Number} bar-height 滑块高度,单位rpx(默认6)
  38. * @property {String Number} item-width 标签的宽度(默认auto)
  39. * @property {String Number} gutter 单个tab标签的左右内边距之和,单位rpx(默认40)
  40. * @property {String} bg-color tabs导航栏的背景颜色(默认#ffffff)
  41. * @property {String} name 组件内部读取的list参数中的属性名(tab名称),见官网说明(默认name)
  42. * @property {String} count 组件内部读取的list参数中的属性名(badge徽标数),同name属性的使用,见官网说明(默认count)
  43. * @property {Array} offset 设置badge徽标数的位置偏移,格式为 [x, y],也即设置的为top和right的值,单位rpx(默认[5, 20])
  44. * @property {Boolean} bold 激活选项的字体是否加粗(默认true)
  45. * @event {Function} change 点击标签时触发
  46. * @example <u-tabs ref="tabs" :list="list" :is-scroll="false"></u-tabs>
  47. */
  48. export default {
  49. name: "u-tabs",
  50. emits: ["update:modelValue", "input", "change"],
  51. props: {
  52. // 通过双向绑定控制组件的弹出与收起
  53. value: {
  54. type: [Number, String],
  55. default: 0
  56. },
  57. modelValue: {
  58. type: [Number, String],
  59. default: 0
  60. },
  61. // 当前活动tab的索引(请使用 v-model="current" 代替 :current="current" @change="change" 其他不变)
  62. current: {
  63. type: [Number, String],
  64. default: 0
  65. },
  66. // 导航菜单是否需要滚动,如只有2或者3个的时候,就不需要滚动了,此时使用flex平分tab的宽度
  67. isScroll: {
  68. type: Boolean,
  69. default: true
  70. },
  71. //需循环的标签列表
  72. list: {
  73. type: Array,
  74. default () {
  75. return [];
  76. }
  77. },
  78. // 导航栏的高度和行高
  79. height: {
  80. type: [String, Number],
  81. default: 80
  82. },
  83. // 字体大小
  84. fontSize: {
  85. type: [String, Number],
  86. default: 30
  87. },
  88. // 过渡动画时长, 单位ms
  89. duration: {
  90. type: [String, Number],
  91. default: 0.5
  92. },
  93. // 选中项的主题颜色
  94. activeColor: {
  95. type: String,
  96. default: '#2979ff'
  97. },
  98. // 未选中项的颜色
  99. inactiveColor: {
  100. type: String,
  101. default: '#303133'
  102. },
  103. // 菜单底部移动的bar的宽度,单位rpx
  104. barWidth: {
  105. type: [String, Number],
  106. default: 40
  107. },
  108. // 移动bar的高度
  109. barHeight: {
  110. type: [String, Number],
  111. default: 6
  112. },
  113. // 单个tab的左或有内边距(左右相同)
  114. gutter: {
  115. type: [String, Number],
  116. default: 30
  117. },
  118. // 导航栏的背景颜色
  119. bgColor: {
  120. type: String,
  121. default: '#ffffff'
  122. },
  123. // 读取传入的数组对象的属性(tab名称)
  124. name: {
  125. type: String,
  126. default: 'name'
  127. },
  128. // 读取传入的数组对象的属性(徽标数)
  129. count: {
  130. type: String,
  131. default: 'count'
  132. },
  133. // 徽标数位置偏移
  134. offset: {
  135. type: Array,
  136. default: () => {
  137. return [5, 20]
  138. }
  139. },
  140. // 活动tab字体是否加粗
  141. bold: {
  142. type: Boolean,
  143. default: true
  144. },
  145. // 当前活动tab item的样式
  146. activeItemStyle: {
  147. type: Object,
  148. default() {
  149. return {}
  150. }
  151. },
  152. // 是否显示底部的滑块
  153. showBar: {
  154. type: Boolean,
  155. default: true
  156. },
  157. // 底部滑块的自定义样式
  158. barStyle: {
  159. type: Object,
  160. default() {
  161. return {}
  162. }
  163. },
  164. // 标签的宽度
  165. itemWidth: {
  166. type: [Number, String],
  167. default: 'auto'
  168. }
  169. },
  170. data() {
  171. return {
  172. scrollLeft: 0, // 滚动scroll-view的左边滚动距离
  173. tabQueryInfo: [], // 存放对tab菜单查询后的节点信息
  174. componentWidth: 0, // 屏幕宽度,单位为px
  175. scrollBarLeft: 0, // 移动bar需要通过translateX()移动的距离
  176. parentLeft: 0, // 父元素(tabs组件)到屏幕左边的距离
  177. id: this.$u.guid(), // id值
  178. currentIndex: this.current,
  179. barFirstTimeMove: true, // 滑块第一次移动时(页面刚生成时),无需动画,否则给人怪异的感觉
  180. };
  181. },
  182. watch: {
  183. // 监听tab的变化,重新计算tab菜单的布局信息,因为实际使用中菜单可能是通过
  184. // 后台获取的(如新闻app顶部的菜单),获取返回需要一定时间,所以list变化时,重新获取布局信息
  185. list(n, o) {
  186. // list变动时,重制内部索引,否则可能导致超出数组边界的情况
  187. if(n.length !== o.length) this.currentIndex = 0;
  188. // 用$nextTick等待视图更新完毕后再计算tab的局部信息,否则可能因为tab还没生成就获取,就会有问题
  189. this.$nextTick(() => {
  190. this.init();
  191. });
  192. },
  193. current: {
  194. immediate: true,
  195. handler(nVal, oVal) {
  196. // 视图更新后再执行移动操作
  197. this.$nextTick(() => {
  198. this.currentIndex = nVal;
  199. this.scrollByIndex();
  200. });
  201. }
  202. },
  203. valueCom: {
  204. immediate: true,
  205. handler(nVal, oVal) {
  206. // 视图更新后再执行移动操作
  207. this.$nextTick(() => {
  208. this.currentIndex = nVal;
  209. this.scrollByIndex();
  210. });
  211. }
  212. }
  213. },
  214. computed: {
  215. valueCom() {
  216. // #ifdef VUE2
  217. return this.value;
  218. // #endif
  219. // #ifdef VUE3
  220. return this.modelValue;
  221. // #endif
  222. },
  223. // 移动bar的样式
  224. tabBarStyle() {
  225. let style = {
  226. width: this.barWidth + 'rpx',
  227. transform: `translate(${this.scrollBarLeft}px, -100%)`,
  228. // 滑块在页面渲染后第一次滑动时,无需动画效果
  229. 'transition-duration': `${this.barFirstTimeMove ? 0 : this.duration }s`,
  230. 'background-color': this.activeColor,
  231. height: this.barHeight + 'rpx',
  232. // 设置一个很大的值,它会自动取能用的最大值,不用高度的一半,是因为高度可能是单数,会有小数出现
  233. 'border-radius': `${this.barHeight / 2}px`
  234. };
  235. Object.assign(style, this.barStyle);
  236. return style;
  237. },
  238. // tab的样式
  239. tabItemStyle() {
  240. return (index) => {
  241. let style = {
  242. height: this.height + 'rpx',
  243. 'line-height': this.height + 'rpx',
  244. 'font-size': this.fontSize + 'rpx',
  245. 'transition-duration': `${this.duration}s`,
  246. padding: this.isScroll ? `0 ${this.gutter}rpx` : '',
  247. flex: this.isScroll ? 'auto' : '1',
  248. width: this.$u.addUnit(this.itemWidth)
  249. };
  250. // 字体加粗
  251. if (index == this.currentIndex && this.bold) style.fontWeight = 'bold';
  252. if (index == this.currentIndex) {
  253. style.color = this.activeColor;
  254. // 给选中的tab item添加外部自定义的样式
  255. style = Object.assign(style, this.activeItemStyle);
  256. } else {
  257. style.color = this.inactiveColor;
  258. }
  259. return style;
  260. }
  261. }
  262. },
  263. methods: {
  264. // 设置一个init方法,方便多处调用
  265. async init() {
  266. // 获取tabs组件的尺寸信息
  267. let tabRect = await this.$uGetRect('#' + this.id);
  268. // tabs组件距离屏幕左边的宽度
  269. this.parentLeft = tabRect.left;
  270. // tabs组件的宽度
  271. this.componentWidth = tabRect.width;
  272. this.getTabRect();
  273. },
  274. // 点击某一个tab菜单
  275. clickTab(index) {
  276. // 点击当前活动tab,不触发事件
  277. if(index == this.currentIndex) return ;
  278. // 发送事件给父组件
  279. this.$emit('change', index);
  280. this.$emit('input', index);
  281. this.$emit("update:modelValue", index);
  282. },
  283. // 查询tab的布局信息
  284. getTabRect() {
  285. // 创建节点查询
  286. let query = uni.createSelectorQuery().in(this);
  287. // 历遍所有tab,这里是执行了查询,最终使用exec()会一次性返回查询的数组结果
  288. for (let i = 0; i < this.list.length; i++) {
  289. // 只要size和rect两个参数
  290. query.select(`#u-tab-item-${i}`).fields({
  291. size: true,
  292. rect: true
  293. });
  294. }
  295. // 执行查询,一次性获取多个结果
  296. query.exec(
  297. function(res) {
  298. this.tabQueryInfo = res;
  299. // 初始化滚动条和移动bar的位置
  300. this.scrollByIndex();
  301. }.bind(this)
  302. );
  303. },
  304. // 滚动scroll-view,让活动的tab处于屏幕的中间位置
  305. scrollByIndex() {
  306. // 当前活动tab的布局信息,有tab菜单的width和left(为元素左边界到父元素左边界的距离)等信息
  307. let tabInfo = this.tabQueryInfo[this.currentIndex];
  308. if (!tabInfo) return;
  309. // 活动tab的宽度
  310. let tabWidth = tabInfo.width;
  311. // 活动item的左边到tabs组件左边的距离,用item的left减去tabs的left
  312. let offsetLeft = tabInfo.left - this.parentLeft;
  313. // 将活动的tabs-item移动到屏幕正中间,实际上是对scroll-view的移动
  314. let scrollLeft = offsetLeft - (this.componentWidth - tabWidth) / 2;
  315. this.scrollLeft = scrollLeft < 0 ? 0 : scrollLeft;
  316. // 当前活动item的中点点到左边的距离减去滑块宽度的一半,即可得到滑块所需的移动距离
  317. let left = tabInfo.left + tabInfo.width / 2 - this.parentLeft;
  318. // 计算当前活跃item到组件左边的距离
  319. this.scrollBarLeft = left - uni.upx2px(this.barWidth) / 2;
  320. // 第一次移动滑块的时候,barFirstTimeMove为true,放到延时中将其设置false
  321. // 延时是因为scrollBarLeft作用于computed计算时,需要一个过程需,否则导致出错
  322. if(this.barFirstTimeMove == true) {
  323. setTimeout(() => {
  324. this.barFirstTimeMove = false;
  325. }, 100)
  326. }
  327. }
  328. },
  329. mounted() {
  330. this.init();
  331. }
  332. };
  333. </script>
  334. <style lang="scss" scoped>
  335. @import "../../libs/css/style.components.scss";
  336. view,
  337. scroll-view {
  338. box-sizing: border-box;
  339. }
  340. /* #ifndef APP-NVUE */
  341. ::-webkit-scrollbar,
  342. ::-webkit-scrollbar,
  343. ::-webkit-scrollbar {
  344. display: none;
  345. width: 0 !important;
  346. height: 0 !important;
  347. -webkit-appearance: none;
  348. background: transparent;
  349. }
  350. /* #endif */
  351. .u-scroll-box {
  352. position: relative;
  353. /* #ifdef MP-TOUTIAO */
  354. white-space: nowrap;
  355. /* #endif */
  356. }
  357. /* #ifdef H5 */
  358. // 通过样式穿透,隐藏H5下,scroll-view下的滚动条
  359. scroll-view ::v-deep ::-webkit-scrollbar {
  360. display: none;
  361. width: 0 !important;
  362. height: 0 !important;
  363. -webkit-appearance: none;
  364. background: transparent;
  365. }
  366. /* #endif */
  367. .u-scroll-view {
  368. width: 100%;
  369. white-space: nowrap;
  370. position: relative;
  371. }
  372. .u-tab-item {
  373. position: relative;
  374. /* #ifndef APP-NVUE */
  375. display: inline-block;
  376. /* #endif */
  377. text-align: center;
  378. transition-property: background-color, color;
  379. }
  380. .u-tab-bar {
  381. position: absolute;
  382. bottom: 0;
  383. }
  384. .u-tabs-scroll-flex {
  385. @include vue-flex;
  386. justify-content: space-between;
  387. }
  388. </style>