element-admin 点击侧边栏刷新当前路由

需求:点击左菜单刷新当前路由页面。javascript

经过查询资料,找到两种实现方式vue

第1种:在路由后面加上时间戳,经过不断改变 url 的 query 来触发 view 的变化,监听侧边栏每一个 link 的 click 事件,每次点击都给 router push 一个不同的 query 来确保会从新刷新 view。java

// 路径地址: src\views\layout\components\Sidebar\Link.vue
export default {
  props: {
    to: {
      type: String,
      required: true
    }
  },
  methods: {
    testClick(url) {
      sessionStorage.setItem('defaultActive', JSON.stringify(url))
      // 经过时间戳实现菜单刷新
      this.$router.push({
        path: url,
        query: {
          t: +new Date() // 保证每次点击路由的query项都是不同的,确保会从新刷新view
        }
      })
    },
    linkProps(url) {
      return {
        is: 'div'
      }
    }
  }
}

存在问题:点击后路由后面都加了一串时间戳致使累赘,另外虽然模拟了刷新了当前页面,但实际并无从新请求接口session

第2种,花裤衩提供的方法,建立一个空的Redirect页面,经过判断当前点击的菜单路由和当前的路由是否一致,一致的时候,会先跳转到专门 Redirect 的页面,而后将路由重定向到我想去的页面,这样就起到了刷新的效果了。展现方式如图1ide

 

//  1.  src\utils\request.js  首先添加路由
{
    path: '/redirect', // 重定向路由
    // component: () => import('@/views/layout/components/Sidebar/redirect'), hidden: true
    component: Layout,
    hidden: true,
    children: [{
      path: '',
      component: () => import('@/views/layout/components/Sidebar/redirect')
    }]
},



//  2.  src\views\layout\components\Sidebar\redirect.vue 添加以下代码 进行重定向
<script>
export default {
  beforeCreate() {
    const { query } = this.$route
    const path = query.path
    this.$router.replace({ path: path })
  },
  mounted() {},
  render: function(h) {
    return h() // avoid warning message
  }
}
</script>



//  3.  src\views\layout\components\Sidebar\Link.vue 菜单页面添加以下代码 进行跳转 

<template>
  <!-- eslint-disable vue/require-component-is -->
  <component v-bind="linkProps(to)" @click="testClick(to)">
    <slot/>
  </component>
</template>

<script>
// import { isExternal } from '@/utils/validate'

export default {
  props: {
    to: {
      type: String,
      required: true
    }
  },
  methods: {
    testClick(url) {
      // 经过重定向空白路由页面实现当前菜单刷新
      if (JSON.parse(sessionStorage.getItem('defaultActive')) === url) {
        // 点击的是当前路由 手动重定向页面到 '/redirect' 页面
        sessionStorage.setItem('defaultActive', JSON.stringify(url))
        const fullPath = encodeURI(url)
        this.$router.replace({
          path: '/redirect',
          query: {
            path: encodeURI(fullPath)
          }
        })
      } else {
        sessionStorage.setItem('defaultActive', JSON.stringify(url))
        // 正常跳转
        this.$router.push({
          path: url
        })
      }
    },
    linkProps(url) {
      return {
        is: 'div'
      }
    }
  }
}
</script>

如上,便可实现点击当前菜单实现页面刷新,两种方案各有利弊,各位小伙伴若有更好的实现方式欢迎留言和私信。post

参考:手摸手,带你用vue撸后台 系列五(v4.0新版本)ui

相关文章
相关标签/搜索