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

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

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

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

// 路径地址: 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'
      }
    }
  }
}

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

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

//  1.  src\router\index.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>

转载于https://my.oschina.net/lemonfive/blog/3050003

posted @ 2020-08-26 16:36  niniHan  阅读(1702)  评论(0编辑  收藏  举报