uni-tabs.vue 12 KB

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