vue技术栈vue

类似浏览器标签页导航

2019-01-18  本文已影响1人  微little

一.想要实现的效果

效果图如下

效果图

二.实现步骤

具体代码如下 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>
上一篇 下一篇

猜你喜欢

热点阅读