vue + elementUI 实现顶部路由标签跳转

vue + elementUI 实现顶部路由标签跳转

引言

后台管理系统中,为了方便使用者跳转已经访问过的页面,需要实现顶部路由标签跳转到访问过页面的功能,因此封装成组件方便使用

封装组件

<!-- TagsView/levelScroll.vue -->    
<template>
  <el-scrollbar
    ref="scrollContainer"
    :vertical="false"
    class="scroll-container"
    @wheel.native.prevent="handleScroll"
  >
    <slot />
  </el-scrollbar>
</template>

<script lang="ts">
import Vue from 'vue';

export default Vue.extend({
      
      
  data () {
      
      
    return {
      
      
      left: 0
    };
  },
  computed: {
      
      
    scrollWrapper () {
      
      
      return (this.$refs as any).scrollContainer.$refs.wrap;
    }
  },
  methods: {
      
      
    // 鼠标滑动事件
    handleScroll (e: {
       
        wheelDelta: number; deltaY: number }) {
      
      
      const eventDelta = e.wheelDelta || -e.deltaY * 40;
      const $scrollWrapper = this.scrollWrapper;
      $scrollWrapper.scrollLeft = $scrollWrapper.scrollLeft + eventDelta / 4;
    }
  }
});
</script>

<style lang="less" scoped>
.scroll-container {
      
      
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  width: 100%;
  /deep/.el-scrollbar__bar {
      
      
    bottom: 0px;
  }
  /deep/.el-scrollbar__wrap {
      
      
    height: 49px;
    // margin-bottom: -17px !important;
    // margin-right: -17px !important;
  }
}
</style>

<!-- TagsView/index.vue -->
<template>
  <div class="tags-view-container">
    <level-scroll ref="levelScroll" class="tags-view-wrapper">
      <router-link
        v-for="tag in visitedViews"
        ref="tag"
        :key="tag.path"
        :class="isActive(tag) ? 'active' : ''"
        :to="{ path: tag.path }"
        tag="span"
        class="tags-view-item"
        @contextmenu.prevent.native="openMenu($event, tag)"
      >
        {
   
   { tag.meta.title }}
        <span
          v-if="!isAffix(tag)"
          class="el-icon-close"
          @click.prevent.stop="closeSelectedTag(tag)"
        />
      </router-link>
    </level-scroll>
    <ul
      v-show="visible"
      :style="{ left: left + 'px', top: top + 'px' }"
      class="contextmenu"
    >
      <li @click="refreshSelectedTag(selectedTag)">刷新页面</li>
      <li v-if="!isAffix(selectedTag)" @click="closeSelectedTag(selectedTag)">
        关闭
      </li>
      <li @click="closeOthersTags(selectedTag)">关闭其他</li>
      <li @click="closeAllTags(selectedTag)">全部关闭</li>
    </ul>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';
import {
      
       mapGetters, mapActions } from 'vuex';
import levelScroll from './levelScroll.vue';

export default Vue.extend({
      
      
  data () {
      
      
    return {
      
      
      // 菜单是否显示
      visible: false,
      // 菜单显示偏移量
      top: 0,
      left: 0,
      // 选择的标签
      selectedTag: {
      
      }
    };
  },
  computed: {
      
      
    ...mapGetters(['visitedViews'])
  },
  methods: {
      
      
    ...mapActions([
      'tagsView/addView',
      'tagsView/delView',
      'tagsView/delOthersViews',
      'tagsView/delAllViews',
      'tagsView/delCachedView'
    ]),
    // 添加跳转的路由标签
    addTags () {
      
      
      const {
      
       name } = this.$route;
      if (name) {
      
      
        this['tagsView/addView'](this.$route);
      }
    },
    // 激活当前页面所对应的标签
    isActive (route: {
       
        path: string }) {
      
      
      return route.path === this.$route.path;
    },
    // 标签是否固定
    isAffix (tag: {
       
        meta: {
       
        affix: boolean } }) {
      
      
      return tag.meta && tag.meta.affix;
    },
    // 右键打开菜单
    openMenu (e: {
       
        clientX: number; clientY: number }, tag: any) {
      
      
      const menuMinWidth = 100;
      // 距离侧边栏的 left
      const offsetLeft = this.$el.getBoundingClientRect().left;
      // tagsView 的宽度
      const offsetWidth = (this.$el as any).offsetWidth;
      // 距离侧边栏最大 left
      const maxLeft = offsetWidth - menuMinWidth;
      // 标签之间 right 为 15
      const left = e.clientX - offsetLeft + 15;

      left > maxLeft ? (this.left = maxLeft) : (this.left = left);
      // top 值需要扣除顶部头部的高度
      this.top = e.clientY - 60;
      this.visible = true;
      this.selectedTag = tag;
    },
    // 关闭菜单
    closeMenu () {
      
      
      this.visible = false;
    },
    // 刷新当前页面
    refreshSelectedTag (selectedTag: {
       
        fullPath: string }) {
      
      
      this['tagsView/delCachedView'](selectedTag);
      const {
      
       fullPath } = selectedTag;
      this.$nextTick(() => {
      
      
        this.$router.replace({
      
      
          path: '/redirect' + fullPath
        });
      });
    },
    // 关闭当前标签
    closeSelectedTag (selectedTag: {
       
        path: string }) {
      
      
      this['tagsView/delView'](selectedTag);
      if (this.isActive(selectedTag)) {
      
      
        this.toLastView();
      }
    },
    // 关闭当前标签之外的其他标签
    closeOthersTags (selectedTag: any) {
      
      
      this['tagsView/delOthersViews'](selectedTag);
      if (!this.isActive(selectedTag)) {
      
      
        this.$router.push(this.selectedTag);
      }
    },
    // 关闭全部标签
    closeAllTags (selectedTag: {
       
        meta: {
       
        title: string } }) {
      
      
      this['tagsView/delAllViews']();
      if (selectedTag.meta && selectedTag.meta.title === '首页') {
      
      
        return;
      }
      this.$router.push({
      
       name: 'Dashboard' });
    },
    // 跳转到路由标签最后一项
    toLastView () {
      
      
      const latestView = this.visitedViews.slice(-1)[0];
      this.$router.push(latestView.path);
    }
  },
  mounted () {
      
      
    this.addTags();
  },
  components: {
      
      
    levelScroll
  },
  watch: {
      
      
    $route () {
      
      
      this.addTags();
    },
    visible (value) {
      
      
      if (value) {
      
      
        document.body.addEventListener('click', this.closeMenu);
      } else {
      
      
        document.body.removeEventListener('click', this.closeMenu);
      }
    }
  }
});
</script>

<style lang="less" scoped>
.tags-view-container {
      
      
  height: 34px;
  width: 100%;
  background: #f2f2f2;
  border-bottom: 1px solid #d8dce5;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 0 3px 0 rgba(0, 0, 0, 0.04);
  .tags-view-wrapper {
      
      
    .tags-view-item {
      
      
      display: inline-block;
      position: relative;
      cursor: pointer;
      height: 26px;
      line-height: 26px;
      border: 1px solid #d8dce5;
      color: #495060;
      background: #fff;
      padding: 0 8px;
      font-size: 12px;
      margin-left: 5px;
      margin-top: 4px;
      &:first-of-type {
      
      
        margin-left: 15px;
      }
      &:last-of-type {
      
      
        margin-right: 15px;
      }
      &.active {
      
      
        background-color: #42b983;
        color: #fff;
        border-color: #42b983;
        &::before {
      
      
          content: "";
          background: #fff;
          display: inline-block;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          position: relative;
          margin-right: 2px;
        }
      }

      .el-icon-close {
      
      
        width: 16px;
        height: 16px;
        vertical-align: 2px;
        border-radius: 50%;
        text-align: center;
        transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
        transform-origin: 100% 50%;
        &:before {
      
      
          transform: scale(0.6);
          display: inline-block;
          vertical-align: -3px;
        }
        &:hover {
      
      
          background-color: #b4bccc;
          color: #fff;
        }
      }
    }
  }
  .contextmenu {
      
      
    margin: 0;
    background: #fff;
    z-index: 50;
    position: absolute;
    list-style-type: none;
    padding: 5px 0;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 400;
    color: #333;
    box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
    li {
      
      
      margin: 0;
      padding: 7px 16px;
      cursor: pointer;
      &:hover {
      
      
        background: #eee;
      }
    }
  }
}
</style>

vuex 文件

// modules/tagsView.ts
const state = {
    
    
  // 访问过的页面标签
  visitedViews: [
    {
    
    
      path: '/dashboard/index',
      meta: {
    
     title: '首页', affix: true }
    }
  ],
  // 访问过的页面的 name 值
  cachedViews: []
};

const mutations = {
    
    
  // 添加访问过的路由
  ADD_VISITED_VIEW: (state: {
    
     visitedViews: any[] }, view: any) => {
    
    
    if (state.visitedViews.some((v) => v.path === view.path)) return;
    state.visitedViews.push(
      Object.assign({
    
    }, view, {
    
    
        title: view.meta.title
      })
    );
  },
  // 添加访问过的路由 name
  ADD_CACHED_VIEW: (state: {
    
     cachedViews: any[] }, view: {
    
     name: string }) => {
    
    
    if (state.cachedViews.includes(view.name)) return;
    state.cachedViews.push(view.name);
  },

  // 删除当前路由
  DEL_VISITED_VIEW: (
    state: {
    
     visitedViews: any[] },
    view: {
    
     path: string }
  ) => {
    
    
    for (const [i, v] of state.visitedViews.entries()) {
    
    
      if (v.path === view.path) {
    
    
        state.visitedViews.splice(i, 1);
        break;
      }
    }
  },
  // 删除当前路由 name
  DEL_CACHED_VIEW: (state: {
    
     cachedViews: any[] }, view: {
    
     name: string }) => {
    
    
    const index = state.cachedViews.indexOf(view.name);
    index > -1 && state.cachedViews.splice(index, 1);
  },

  // 删除当前路由之外的路由
  DEL_OTHERS_VISITED_VIEWS: (
    state: {
    
     visitedViews: any[] },
    view: {
    
     path: string }
  ) => {
    
    
    state.visitedViews = state.visitedViews.filter((v) => {
    
    
      return v.meta.affix || v.path === view.path;
    });
  },
  // 删除当前路由之外的路由 name
  DEL_OTHERS_CACHED_VIEWS: (
    state: {
    
     cachedViews: any[] },
    view: {
    
     name: string }
  ) => {
    
    
    const index = state.cachedViews.indexOf(view.name);
    if (index > -1) {
    
    
      state.cachedViews = state.cachedViews.slice(index, index + 1);
    } else {
    
    
      state.cachedViews = [];
    }
  },

  // 删除全部访问过的路由
  DEL_ALL_VISITED_VIEWS: (state: {
    
     visitedViews: any[] }) => {
    
    
    const affixTags = state.visitedViews.filter((tag) => tag.meta.affix);
    state.visitedViews = affixTags;
  },
  // 删除全部访问过的路由 name
  DEL_ALL_CACHED_VIEWS: (state: {
    
     cachedViews: any[] }) => {
    
    
    state.cachedViews = [];
  }
};

const actions = {
    
    
  // 添加访问过的路由
  addVisitedView ({
    
     commit }: {
    
     commit: any }, view: any) {
    
    
    commit('ADD_VISITED_VIEW', view);
  },
  // 添加访问过的路由 name
  addCachedView ({
    
     commit }: {
    
     commit: any }, view: any) {
    
    
    commit('ADD_CACHED_VIEW', view);
  },
  addView ({
    
     dispatch }: {
    
     dispatch: any }, view: any) {
    
    
    dispatch('addVisitedView', view);
    dispatch('addCachedView', view);
  },

  // 删除当前路由
  delVisitedView ({
    
     commit }: {
    
     commit: any }, view: any) {
    
    
    commit('DEL_VISITED_VIEW', view);
  },
  // 删除当前路由 name
  delCachedView ({
    
     commit }: {
    
     commit: any }, view: any) {
    
    
    commit('DEL_CACHED_VIEW', view);
  },
  delView ({
    
     dispatch }: {
    
     dispatch: any }, view: any) {
    
    
    dispatch('delVisitedView', view);
    dispatch('delCachedView', view);
  },

  // 删除当前路由之外的路由
  delOthersVisitedViews ({
    
     commit }: {
    
     commit: any }, view: any) {
    
    
    commit('DEL_OTHERS_VISITED_VIEWS', view);
  },
  // 删除当前路由之外的路由 namw
  delOthersCachedViews ({
    
     commit }: {
    
     commit: any }, view: any) {
    
    
    commit('DEL_OTHERS_CACHED_VIEWS', view);
  },
  delOthersViews ({
    
     dispatch }: {
    
     dispatch: any }, view: any) {
    
    
    dispatch('delOthersVisitedViews', view);
    dispatch('delOthersCachedViews', view);
  },

  // 删除全部访问过的路由
  delAllVisitedViews ({
    
     commit }: {
    
     commit: any }) {
    
    
    commit('DEL_ALL_VISITED_VIEWS');
  },
  // 删除全部访问过的路由 name
  delAllCachedViews ({
    
     commit }: {
    
     commit: any }) {
    
    
    commit('DEL_ALL_CACHED_VIEWS');
  },
  delAllViews ({
    
     dispatch }: {
    
     dispatch: any }, view: any) {
    
    
    dispatch('delAllVisitedViews', view);
    dispatch('delAllCachedViews', view);
  }
};

export default {
    
    
  namespaced: true,
  state,
  mutations,
  actions
};

// getters.ts
const getters = {
    
    
  // 访问的页面标签
  visitedViews: (state: any) => state.tagsView.visitedViews,
  // 访问的页面标签 name
  cachedViews: (state: any) => state.tagsView.cachedViews
};
export default getters;

router 文件

import Vue from 'vue';
import VueRouter from 'vue-router';
import Login from '@/views/login/index.vue';
import Layout from '@/layout/index.vue';

Vue.use(VueRouter);

/**
 * hidden 表示是否需要在侧边导航栏出现 ,true表示不需要
 * isFirst 表示是否只有一级权限,只出现在只有一个子集,没有其他孙子集
 * 当权限拥有多个子集或者孙子集,一级权限需要加上 meta
 * 二级权限拥有子集,也必须有 meta
 */

// 基础路由
export const constantRoutes = [
  {
    
    
    path: '/redirect',
    component: Layout,
    hidden: true,
    children: [
      {
    
    
        path: '/redirect/:path(.*)',
        component: () => import('@/views/redirect/index.vue')
      }
    ]
  },
  {
    
    
    path: '/',
    redirect: '/dashboard',
    hidden: true
  },
  {
    
    
    path: '/login',
    name: 'Login',
    component: Login,
    hidden: true
  },
  {
    
    
    path: '/dashboard',
    component: Layout,
    redirect: '/dashboard/index',
    isFirst: true,
    children: [
      {
    
    
        path: 'index',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: {
    
    
          title: '首页',
          icon: 'el-icon-location'
        }
      }
    ]
  }
];

// 动态路由
export const asyncRoutes = [
  {
    
    
    path: '/form',
    component: Layout,
    redirect: '/form/index',
    isFirst: true,
    children: [
      {
    
    
        path: 'index',
        name: 'Form',
        component: () => import('@/views/form/index.vue'),
        meta: {
    
    
          title: '表单',
          role: 'form',
          icon: 'el-icon-location'
        }
      }
    ]
  },
  {
    
    
    path: '/editor',
    component: Layout,
    redirect: '/editor/index',
    meta: {
    
    
      role: 'editors',
      title: '总富文本',
      icon: 'el-icon-location'
    },
    children: [
      {
    
    
        path: 'index',
        name: 'Editor',
        component: () => import('@/views/editor/index.vue'),
        meta: {
    
    
          title: '富文本',
          role: 'editor',
          icon: 'el-icon-location'
        }
      },
      {
    
    
        path: 'two',
        name: 'Two',
        redirect: '/editor/two/three',
        component: () => import('@/views/editor/two.vue'),
        meta: {
    
    
          title: '二级导航',
          role: 'two',
          icon: 'el-icon-location'
        },
        children: [
          {
    
    
            path: 'three',
            name: 'Three',
            component: () => import('@/views/editor/three.vue'),
            meta: {
    
    
              title: '三级导航',
              role: 'three',
              icon: 'el-icon-location'
            }
          },
          {
    
    
            path: 'four',
            name: 'Four',
            component: () => import('@/views/editor/four.vue'),
            meta: {
    
    
              title: '三级导航2',
              role: 'four',
              icon: 'el-icon-location'
            }
          }
        ]
      }
    ]
  },
  {
    
    
    path: '/tree',
    component: Layout,
    redirect: '/tree/index',
    isFirst: true,
    children: [
      {
    
    
        path: 'index',
        name: 'Tree',
        component: () => import('@/views/tree/index.vue'),
        meta: {
    
    
          title: '树状图',
          role: 'tree',
          icon: 'el-icon-location'
        }
      }
    ]
  },
  {
    
    
    path: '/excel',
    component: Layout,
    redirect: '/excel/index',
    isFirst: true,
    children: [
      {
    
    
        path: 'index',
        name: 'Excel',
        component: () => import('@/views/excel/index.vue'),
        meta: {
    
    
          title: '导入导出',
          role: 'excel',
          icon: 'el-icon-location'
        }
      }
    ]
  }
];

// 出错跳转的路由
export const error = [
  // 404
  {
    
    
    path: '/404',
    component: () => import('@/views/error/index.vue'),
    hidden: true
  },
  {
    
    
    path: '*',
    redirect: '/404',
    hidden: true
  }
];

const createRouter = () =>
  new VueRouter({
    
    
    scrollBehavior: () => ({
    
    
      x: 0,
      y: 0
    }),
    routes: constantRoutes
  });

const router = createRouter();

// 刷新路由
export function resetRouter () {
    
    
  const newRouter = createRouter();
  (router as any).matcher = (newRouter as any).matcher;
}

export default router;

页面中使用

<!-- 一般在主体布局页面使用 -->
<template>
  <div class="layout">
     ......
    <el-container :class="{ hideSidebar: isCollapse }">
      ......
      <!-- 主体内容 -->
      <el-main>
        <!-- 访问过的路由标签 -->
        <tags-view></tags-view>
        <keep-alive :include="cachedViews">
          <router-view :key="$route.path" />
        </keep-alive>
      </el-main>
    </el-container>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';
import {
      
       mapGetters } from 'vuex';
import SubMenu from '@/components/SubMenu/index.vue';
import MyBreadcrumb from '@/components/Breadcrumb/index.vue';
import TagsView from '@/components/TagsView/index.vue';
import {
      
       resetRouter } from '@/router';

export default Vue.extend({
      
      
  computed: {
      
      
    // 路由
    ...mapGetters(['cachedViews'])
  },
  components: {
      
      
    TagsView
  }
});
</script>

参考网上资料进行封装修改,具体需求可根据项目修改

猜你喜欢

转载自blog.csdn.net/m0_64344940/article/details/122966283
今日推荐