vue项目实现TagsView的功能

4,088 阅读3分钟

效果图


1.新建TagsView.vue

<template>
     <div class="tags-view-container">
          <scroll-pane class="tags-view-wrapper" ref="scrollPane">
              <router-link ref="tag"  class="isActive(tag)?'active':''"  :to="tag"  @contextmenu.prevent.native="openMenu(tag,$event)" v-for="tag in Array.from(visitedViews)" :key="tag.path" >
                {{tag.title}}
                  <span class="el-icon-close" @click.prevent.stop='closeSelectedTag(tag)'></span>
              </router-link>
          </scroll-pane>
     </div>
</template>
 
<script>
  import ScrollPane from '@/components/ScrollPane'
    export default {
        name: "tags-view",
      components: { ScrollPane },
     data(){
          return{
          }
     },
      computed:{
          visitedViews(){
            return this.$store.state.tagsView.visitedViews
          }
      },
      watch:{
         $route(){
           this.addViewTags()
           this.moveToCurrentTag()
         },
        visible(value) {
          if (value) {
            document.body.addEventListener('click', this.closeMenu)
          } else {
            document.body.removeEventListener('click', this.closeMenu)
          }
        }
      },
      mounted() {
        this.addViewTags()
      },
      methods:{
          generateRoute(){
            if (this.$route.name) {
              return this.$route
            }
            return false
          },
        isActive(route) {
          return route.path === this.$route.path
        },
        addViewTags() {
          const route = this.generateRoute()
          if (!route) {
            return false
          }
          this.$store.dispatch('addVisitedViews', route)
        },
        moveToCurrentTag() {
          const tags = this.$refs.tag
          this.$nextTick(() => {
            for (const tag of tags) {
              if (tag.to.path === this.$route.path) {
                this.$refs.scrollPane.moveToTarget(tag.$el)
                break
              }
            }
          })
        },
        closeSelectedTag(view) {
          this.$store.dispatch('delVisitedViews', view).then((views) => {
            if (this.isActive(view)) {
              const latestView = views.slice(-1)[0]
              if (latestView) {
                this.$router.push(latestView)
              } else {
                this.$router.push('/')
              }
            }
          })
        },
        openMenu(tag, e) {
          this.visible = true
          this.selectedTag = tag
          const offsetLeft = this.$el.getBoundingClientRect().left // container margin left
          this.left = e.clientX - offsetLeft + 15 // 15: margin right
          this.top = e.clientY
        },
        closeMenu() {
          this.visible = false
        }
      }
    }
</script>
 
<style rel="stylesheet/scss" lang="scss" scoped>
  .tags-view-container {
    .tags-view-wrapper {
      background: #fff;
      height: 34px;
      border-bottom: 1px solid #d8dce5;
      box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .12), 0 0 3px 0 rgba(0, 0, 0, .04);
      .tags-view-item {
        display: inline-block;
        position: relative;
        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;
        }
        &.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;
          }
        }
      }
    }
    .contextmenu {
      margin: 0;
      background: #fff;
      z-index: 100;
      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, .3);
      li {
        margin: 0;
        padding: 7px 16px;
        cursor: pointer;
        &:hover {
          background: #eee;
        }
      }
    }
 .tags-view-wrapper {
    .tags-view-item {
      .el-icon-close {
        width: 16px;
        height: 16px;
        vertical-align: 2px;
        border-radius: 50%;
        text-align: center;
        transition: all .3s cubic-bezier(.645, .045, .355, 1);
        transform-origin: 100% 50%;
        &:before {
          transform: scale(.6);
          display: inline-block;
          vertical-align: -3px;
        }
        &:hover {
          background-color: #b4bccc;
          color: #fff;
        }
      }
    }
  }
}</style>
 

2.ScrollPane.vue:是当tagView内容超出一行时候的滚动(将鼠标悬浮在那一行上,不出现滚动条,该行就可以滚动)

 

<template>  <div class="scroll-container" ref="scrollContainer" @wheel.prevent="handleScroll">    <div class="scroll-wrapper" ref="scrollWrapper" :style="{left: left + 'px'}">      <slot></slot>    </div>  </div></template><script>const padding = 15 // tag's paddingexport default {  name: 'scrollPane',  data () {    return {      left: 0    }  },  methods: {    handleScroll (e) {      const eventDelta = e.wheelDelta || -e.deltaY * 3// wheelDelta:-120;deltaY:-120      const $container = this.$refs.scrollContainer// 外面的container      const $containerWidth = $container.offsetWidth// 外面的container的宽度      const $wrapper = this.$refs.scrollWrapper// 里面      const $wrapperWidth = $wrapper.offsetWidth// 里面的宽度      if (eventDelta > 0) {        this.left = Math.min(0, this.left + eventDelta)// min() 方法可返回指定的数字中带有最低值的数字。      } else {        if ($containerWidth - padding < $wrapperWidth) {          if (this.left < -($wrapperWidth - $containerWidth + padding)) {            this.left = this.left          } else {            this.left = Math.max(this.left + eventDelta, $containerWidth - $wrapperWidth - padding)          }        } else {          this.left = 0        }      }    },    moveToTarget ($target) {      const $container = this.$refs.scrollContainer      const $containerWidth = $container.offsetWidth      const $targetLeft = $target.offsetLeft      const $targetWidth = $target.offsetWidth      if ($targetLeft < -this.left) {        // tag in the left        this.left = -$targetLeft + padding      } else if ($targetLeft + padding > -this.left && $targetLeft + $targetWidth < -this.left + $containerWidth - padding) {        // tag in the current view          // eslint-disable-line      } else {        // tag in the right        this.left = -($targetLeft - ($containerWidth - $targetWidth) + padding)      }    }  }}</script><style rel="stylesheet/scss" lang="scss" scoped>  .scroll-container {    white-space: nowrap;    position: relative;    overflow: hidden;    width: 100%;    .scroll-wrapper {      position: absolute;    }  }</style>

3.store/modules/tagsView.js

引入vuex,并做本地永久保存,有问题的可以看上片文章

import { getStore, setStore } from '@/utils/store'
const tagsView = {
 state: {    visitedViews: getStore({ name: 'visitedViews' }) || [],    cachedViews: getStore({ name: 'cachedViews' }) || []  },
  mutations: {    ADD_VISITED_VIEWS: (state, view) => {      if (state.visitedViews.some(v => v.name === view.name)) return      state.visitedViews.push({        name: view.name,        path: view.fullPath,        title: view.meta.title || 'no-name'      })      setStore({        name: 'visitedViews',        content: state.visitedViews,        type: 'session'      })      if (!view.meta.noCache) {        state.cachedViews.push(view.name)        setStore({          name: 'cachedViews',          content: state.cachedViews,          type: 'session'        })      }    },    DEL_VISITED_VIEWS: (state, view) => {      for (const [i, v] of state.visitedViews.entries()) {        if (v.path === view.path) {          state.visitedViews.splice(i, 1)          setStore({            name: 'visitedViews',            content: state.visitedViews,            type: 'session'          })          break        }      }      for (const i of state.cachedViews) {        if (i === view.name) {          const index = state.cachedViews.indexOf(i)          state.cachedViews.splice(index, 1)          setStore({            name: 'cachedViews',            content: state.cachedViews,            type: 'session'          })          break        }      }    }  },  actions: {    addVisitedViews ({ commit }, view) {      commit('ADD_VISITED_VIEWS', view)    },    delVisitedViews ({ commit, state }, view) {      return new Promise((resolve) => {        commit('DEL_VISITED_VIEWS', view)        resolve([...state.visitedViews])      })    }  }}
 
export default tagsView 

4.将tagsView.js引入到store/index.js中

import tagsView from './modules/tagsView'
export default new Vuex.Store({  modules: {    tagsView  }})

5.注意

别忘了在路由上面加name属性,例如

 {      path: '/changePassword',      component: () => import('@/components/Layout.vue'),      children: [1        {          path: '/',          name: 'changePassword',          meta: { title: '修改密码' },          component: () => import('@/view/changePassword')        }      ]    },