vue组件之吸顶展示选项条

在开发移动端项目中,经常会使用到吸顶展示的选项导航如下图所示:

在这里插入图片描述

而且此选项导航条在距顶部一定距离时,会固定住不再向上滚动

分析一下:

在这里插入图片描述

先创建一个tabControl.vue

<template>
  <div class="tab-control">
    <div class="tab-control-item">
      <span>写死的</span>
      <span>等等传</span>
      <span>从父级传</span>
    </div>
  </div>
</template>

<script>
  export default {
     
     
    name: 'TabControl',  
  }
</script>

灰色外部包裹为最外部div,给个class="tab-control"方便等等进行细节优化

由于每个tabItem项都是只有文字,也先用div包裹,给个class=“tab-control-item”,直接用一个简单的span先来占个位

开始加以css修饰:flex布局,文字居中,给这个选项条设置高度:40px,再设置个背景颜色,那么里面每个tabItem就是flex:1

<style scoped>
  .tab-control {
    
    
    display: flex;
    text-align: center;
    font-size: 15px;
    height: 40px;
    line-height: 40px;
    background-color: #ccc;
  }
  
  .tab-control-item {
    
    
    flex: 1;
  }

</style>

每个tabItem里面的文字和span的数量,是由使用此组件的父组件决定的,所以由父级组件传值过来就行。在上述中知道tabItem只是文字展示,那么用一个数组来存储和传值即可。

父级组件引用并传值:

<template>
  <div id="home">
    
    <tab-control :titles="titles"></tab-control>
 
  </div>
</template>

<script>

  import TabControl from '@components/content/TabControl/TabControl'

  export default {
     
     
    name: 'Home',
    data() {
     
     
      return {
     
     
        
        titles:['推荐','建议','问候']
        
      }
    },
    components: {
     
          
      TabControl
    },
   
  }
</script>

<style scoped>

</style>

父级传过去titles数组,里面包含[“推荐”, "建议”,“问候”] 三个元素,也代表着会创建三个tabItem,三个span

子组件的接收

<template>
  <div class="tab-control">
    <div
      v-for="(item,index) in titles"
      :key="index"
      class="tab-control-item"
    >
      <span>{
   
   {item}}</span>
    </div>
  </div>
</template>

<script>
  export default {
     
     
    name: 'TabControl',
    props: {
     
     
      titles: {
     
     
        type: Array,
        default() {
     
     
          return []
        }
      }
    },
  }
</script>

以上就可以将父组件中传过来的数组展示出来了。

点击某个选项,该选项高亮,首先用点击事件获取当前点击的该项的index值,再设置某个特定的css样式:active,让该选项应用active样式

<template>
  <div class="tab-control">
    <div
      v-for="(item,index) in titles"
      :key="index"
      class="tab-control-item"
      :class="{active: index === currentIndex}"  ----动态绑定样式
      @click="ItemClick(index)"  ----点击事件获取index
    >
      <span>{
   
   {item}}</span>
    </div>
  </div>
</template>
data() {
    
    
      return {
    
    
        currentIndex: 0  // 初始index默认为0
      }
    },
    methods: {
    
    
      ItemClick(index) {
    
    
        this.currentIndex = index // 将当前点击的那一项的index赋值给currentIndex
      }
    }
  .active {
    
    
    color: black;
  }
  
  .active span {
    
    
    border-bottom: 3px solid red;
  }

只有currentIndex 与当前项index相同时,才会激活active样式。

吸顶效果设置:主要是css样式中的position属性

 .tab-control{
    
    
    position: sticky;
    top: 44px;
  }

这个选线条会在距离top 44px的位置position变为:fixed,在距离顶部44px以下,是其活动区域,position为static。

猜你喜欢

转载自blog.csdn.net/michaelxuzhi___/article/details/105939373