vue 自制tabbar 组件

≯℡__Kan透↙ 提交于 2021-01-09 06:37:57

 

原文链接: vue 自制tabbar 组件

一个通过使用tabbar切换路由的组件

 

点击下面的tab,跳转到指定的路由,注意每次该页面激活时需要根据页面的路由来设置对应 的tab为激活状态,否则,再某一页面刷新后可能会出现tab和显示的路由不匹配的问题

<template>
  <div class="tabs">
    <div v-for="tab,index in tabs" :key="index">
      <div class="tab" @click="changeTab(tab,index)">
        <!--:style="'background-image: url('+tab.base+');background-size:100% 100%'" class="tab"-->
        <img :src="cur_index==index ? tab.active : tab.base" alt="" class="tab-img">
        <span class="tab-name" :style="cur_index==index ? 'color: #1296db':'color:rgb(111,111,111)'">{{tab.name}}</span>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: "tab",
    data() {
      return {
        cur_index: 0,
        tabs: [
          {
            active: "/static/imgs/movie_active.png",
            base: "/static/imgs/movie_base.png",
            path: "/main/movie",
            name: '电影'

          },
          {
            active: "/static/imgs/comment_active.png",
            base: "/static/imgs/comment_base.png",
            path: "/main/review",
            name: '影评'
          },
          {
            active: "/static/imgs/collection_active.png",
            base: "/static/imgs/collection_base.png",
            path: "/main/collection/movie",
            name: '收藏'
          },
          {
            active: "/static/imgs/me_active.png",
            base: "/static/imgs/me_base.png",
            path: "/main/me",
            name: '我'
          },
        ]
      }

    },
    methods: {
      changeTab(tab, index) {
        this.$router.push(tab.path)
        this.cur_index = index
      },
      prev() {
        this.cur_index = (this.cur_index + this.tabs.length - 1) % this.tabs.length
        this.$router.push(this.tabs[this.cur_index].path)
      },
      next() {
        this.cur_index = (this.cur_index + 1) % this.tabs.length
        this.$router.push(this.tabs[this.cur_index].path)
      }
    },

    mounted() {
      // 避免刷新后tab 显示的高亮按钮与路由对不上
      var test = window.location.href.split('#')[1];
      this.tabs.forEach(
        (item, index) => {
          console.log(item.path, index)
          if (item.path == test) {
            this.cur_index = index
          }
        })
    }
  }
</script>

<style scoped>

  .tabs {
    display: flex;
    justify-content: space-around;
    background: rgb(233, 233, 233);
    padding: 10px;
  }

  .tab {
    width: 50px;
    height: 50px;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;

  }

  .tab-img {
    width: 30px;
    height: 30px;
  }

  .tab-name {
    font-size: 10px;
    padding: 3px;
  }
</style>

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!