swiper-tab-head.vue 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <template>
  2. <view class="uni-tab-bar">
  3. <scroll-view scroll-x class="uni-swiper-tab content-scroll" :style="scrollStyle" scroll-with-animation :scroll-left="scrollLeft">
  4. <block v-for="(tab,index) in tabBars" :key="index">
  5. <view class="swiper-tab-list scroll-item"
  6. :class="{'active':tabIndex==index}"
  7. @tap="tabtap(index)"
  8. :style="scrollItemStyle">
  9. {{tab.name}} {{tab.num?tab.num:''}}
  10. <view class="swiper-tab-line"></view>
  11. </view>
  12. </block>
  13. </scroll-view>
  14. </view>
  15. </template>
  16. <script>
  17. export default {
  18. data(){
  19. return {
  20. contentScrollW: 0, // 导航区宽度
  21. scrollLeft: 0, // 横向滚动条位置
  22. }
  23. },
  24. props:{
  25. tabBars:Array,
  26. tabIndex:Number,
  27. scrollStyle:{
  28. type:String,
  29. default:""
  30. },
  31. scrollItemStyle:{
  32. type:String,
  33. default:""
  34. }
  35. },
  36. mounted() {
  37. // 获取标题区域宽度,和每个子元素节点的宽度
  38. this.getScrollW()
  39. },
  40. methods:{
  41. tabtap(index){
  42. console.log(index)
  43. this.scrollLeft = this.tabBars[index].left - this.contentScrollW / 2 + this.tabBars[index].width / 2;
  44. this.$emit('tabtap',index);
  45. },
  46. // 获取标题区域宽度,和每个子元素节点的宽度以及元素距离左边栏的距离
  47. getScrollW() {
  48. const query = uni.createSelectorQuery().in(this);
  49. query.select('.content-scroll').boundingClientRect(data => {
  50. // 拿到 scroll-view 组件宽度
  51. this.contentScrollW = data.width
  52. }).exec();
  53. query.selectAll('.scroll-item').boundingClientRect(data => {
  54. let dataLen = data.length;
  55. for (let i = 0; i < dataLen; i++) {
  56. // scroll-view 子元素组件距离左边栏的距离
  57. this.tabBars[i].left = data[i].left;
  58. // scroll-view 子元素组件宽度
  59. this.tabBars[i].width = data[i].width
  60. }
  61. }).exec()
  62. },
  63. }
  64. }
  65. </script>
  66. <style>
  67. .uni-swiper-tab{
  68. border-bottom: 1upx solid #EEEEEE;
  69. }
  70. .swiper-tab-list{
  71. color: #969696;
  72. font-weight: bold;
  73. }
  74. .uni-tab-bar .active{
  75. color: #343434;
  76. }
  77. .active .swiper-tab-line{
  78. border-bottom: 4upx solid #B9B9B9;
  79. width: 70upx;
  80. margin: auto;
  81. border-top: 4upx solid #B9B9B9;
  82. border-radius:20upx;
  83. }
  84. </style>