美文网首页vue技术栈vue
类似浏览器标签页导航

类似浏览器标签页导航

作者: 微little | 来源:发表于2019-01-18 14:44 被阅读1次

一.想要实现的效果

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

效果图如下

效果图

二.实现步骤

  • 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>

相关文章

网友评论

    本文标题:类似浏览器标签页导航

    本文链接:https://www.haomeiwen.com/subject/otdndqtx.html