Vue 项目重复点击菜单刷新当前页面

3,686 阅读1分钟

场景

最近在项目开发过程中,客户提了一个需求:“在当前页面点击当前页面对应的菜单时,也能刷新页面。”

由于 Vue 项目的路由机制是路由不变的情况下,对应的组件是不重新渲染的。所以重复点击菜单不会改变路由,然后页面就无法刷新了。

思路

由于 Vue 路由机制无法改变,所以只能从其他方面着手了。大概有以下 2 种思路:

方案一:改变路由

方案二:借助重定向

实现

方案一:改变路由

在切换路由时,给路由后面加上时间戳,通过每次点击,不断的改变 urlquery 来触发 view 的变化。

// 通过时间戳实现菜单刷新
this.$router.push({
  path: url,
  query: {
    t: +new Date() // 保证每次点击路由的query项都是不一样的,确保会重新刷新view
  }
})

缺点:每次点击后,地址栏地址后面会存在一长串时间戳。

方案二:借助重定向

利用一个空的 redirect 页面,通过判断当前路由是否与点击的路由一致,如果一致,则跳转到 redirect 页面,然后在 redirect 页面重定向回跳转之前的页面。这样就实现了页面刷新了。

  1. 创建一个空的页面:src/layout/components/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>
  1. 挂载路由:src/router/index.js
{
  path: '/redirect',
  component: () => import('@/layout/components/redirect.vue')
},
  1. 菜单跳转的地方添加事件,进行相关处理:
<el-menu ... @select="selectMenuItem">
    // ...
</el-menu>

<script>
export default {
  methods: {
    selectMenuItem (url, indexPath) {
      if (this.$route.fullPath === url) {
        // 点击的是当前路由 手动重定向页面到 '/redirect' 页面
        this.$router.replace({
          path: '/redirect',
          query: {
            path: encodeURI(url)
          }
        })
      } else {
        // 正常跳转
        this.$router.push({
          path: url
        })
      }
    }
  }
}
</script>

结尾总结

方案一 只能算是页面半刷新。我目前项目就采用的 方案二,相对方案一较为灵活,且能实现真正的页面(组件)刷新,

用此种方法,当点击同一菜单时,地址栏每次的变化都是从:http://localhost:8080/#/redirect?path=xxxxxxhttp://localhost:8080/#/xxxxxx