elementUI設置標籤頁

思路:
1、在vuex中存儲點擊過的標籤頁
2、當路由刷新時,將路由添加到vuex中,並判斷當前路由是否已經再標籤頁列表中
3、關閉標籤頁時,將vuex中的路由刪除
代碼:
vuex中保存點擊過的路由列表,新建tagsPages.js文件

const tagsPages= {

    state:{
        //路由列表
        tagsPages:[]
    },

    mutations:{

        //添加路由
        ADD_PAGE(state,page){
            //判斷路由是否已經在列表中,如果存在,不再添加到列表中
            if(state.tagsPages.some(item=>item.path == page.path))
            return;
            //添加路由到列表中
            state.tagsPages.push({
                name: page.name,
                title: page.meta.title,
                path: page.path
             })
        },
        //刪除路由
        DEL_PAGE(state,page){

            for(let[i,p] of state.tagsPages.entries()){
                if(p.path == page.path){
                    state.tagsPages.splice(i,1)
                    break
                }
            }
        }
    },

    actions:{

        //添加路由
        addPage({commit},page){
            commit("ADD_PAGE",page)
        },

       //刪除路由
        delPage({commit, state },page){

            return new Promise((resolve) => {
                commit("DEL_PAGE",page)
                resolve([...state.tagsPages])
            })
           
        }

    }

}
export default tagsPages

添加到vuex中

import Vue from 'vue'
import Vuex from 'vuex'
import tagsPages from './tagsPages'

Vue.use(Vuex)

const store= new Vuex.Store({
  modules:{
    tagsPages
  }
})

export default store

標籤頁組件tagsPage.vue,沒有寫css樣式

<template>
  <div>
    <el-scrollbar
      ref="scrollContainer"
      :vertical="false"
    >
      <router-link
        v-for="tag in tagsPages"
        ref="tag"
        :to="{ path: tag.path}"
        :key="tag.path"
        tag="span"
      >
        <span class="el-icon-close" @click.prevent.stop="closeSelectedTag(tag)" />
        {{ tag.title }}
      </router-link>
    </el-scrollbar>
  </div>
</template>
<script>
export default {
  data() {
    return {
      left: 0
    };
  },
  computed: {
    tagsPages() {
      //從store中獲取點擊過的路由列表
      return this.$store.state.tagsPages.tagsPages ;
    }
  },
  watch: {
      //當路由改變時,添加路由到路由列表
    $route() {
      this.addTagsPage();
    }
  },
  methods: {
    addTagsPage() {
      //路由改變時執行的方法
      if (this.$route.name) {
        const route = this.$route;
        this.$store.dispatch("addPage", route);
      }
    },
    //關閉標籤頁
    closeSelectedTag(view) {
      this.$store.dispatch("delPage", view).then(visitedViews => {
     
         //判斷關閉的標籤頁是不是當前頁
         //如果是當前頁,則判斷路由列表中是否還存在路由
         //如果存在則跳轉到到最後打開的頁面
         //如果不存在則跳轉到首頁
        if (view.path == this.$route.path) {
          const latestView = visitedViews.slice(-1)[0];
          if (latestView) {
            this.$router.push(latestView);
          } else {
            this.$router.push("/");
          }
        }
      });
    }
  }
};
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章