类似浏览器标签页导航

一.想要实现的效果

  • 当前路由切换,跟着改变
  • 重复路由不再添加
  • 删除当前标签,自动返回上一个标签
  • 剩下最后标签无法删除

效果图如下

效果图

二.实现步骤

  • 1.在vuex中存放标签页数组
  • 2.切换路由,添加不重复的标签
  • 3.点击删除图标,删除标签

具体代码如下 tags.js

export default{

    state:{
        visitedviews:[],//存放所有浏览过的且不重复的路由数据
    },
    
     mutations:{
        // 添加标签,重复不添加
        ADD_VISITED_VIEWS:(state,view)=>{
            if(state.visitedviews.some(v=>v.path===view.path)) return;
            state.visitedviews.push({
                name:view.name,
                path:view.path
            })
        },
        // 删除(关闭)标签
        DEL_VISITED_VIEWS:(state,view)=>{
                state.visitedviews.forEach(item=> {
                    if(item.path==view.path){
                        state.visitedviews.splice(state.visitedviews.indexOf(item),1);
                    }
            })
        }
    },
    
    actions:{
        addVisitedViews({commit},view){
            commit('ADD_VISITED_VIEWS',view)
        },
        delVisitedViews({commit,state},view){
            return new Promise(resolve=>{//删除后,需要重新刷新路由,使用resolve
                commit('DEL_VISITED_VIEWS',view);
                resolve([...state.visitedviews])
            })
        }
    }
}

页面渲染 menu.vue

<!-- 类似浏览器标签页导航 -->
<template>
  <div class="tags">
    <router-link class="tab" :to="item.path" v-for="(item,index) in visitedViews" :key="index">
      <el-button :type="item.name==$route.name?'primary':''" size="mini">
          {{item.name}}
          <span v-if="visitedViews.length!=1" class='el-icon-close' @click.prevent.stop="closeTags(item)"></span>
       </el-button>
    </router-link>
  </div>
</template>

<script>
export default {
  data () {
    return {
    };
  },

  components: {},

  computed: {
    visitedViews(){//store中取值
      return this.$store.state.tags.visitedviews
    }
  },
  watch:{
    $route(to,from){
      this.$store.dispatch('addVisitedViews',this.$route)
    }
  },


  methods: {
    //关闭标签页
    closeTags(item){
      this.$store.dispatch('delVisitedViews',item).then(res=>{
        if(item.name==this.$route.name){//关闭当前页时,返回上一个历史页面
          this.$router.push(res[res.length-1].path);
        }
      })
    }
  },

  created(){//设置默认标签页
    this.$store.dispatch('addVisitedViews',this.$route)
  }
}

</script>
<style lang='scss' scoped>
.tags{
  background-color: #fff;
  padding: 10px 20px;
  box-sizing: border-box;
  display: flex;
}
.tab{
  margin-right: 10px;
}
</style>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • VUE Vue :数据驱动的M V Vm框架 m :model(后台提供数据),v :view(页面),vM(模板...
    wudongyu阅读 10,762评论 0 11
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,452评论 4 61
  • 今天一天都在想着怎么写今天的简书,本来想写生活中的一些片段,但是感觉每天写来写去不是老公就是孩子要么就是自己,...
    鑫玺海燕阅读 2,454评论 4 2
  • 临摹图
    白祁艺love阅读 1,423评论 0 0

友情链接更多精彩内容