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

场景

最近在项目开发过程中,项目经理提了一个需求:在当前页面点击当前页面对应的(左侧)菜单时,也能刷新页面。
由于 Vue 项目的路由机制是路由不变的情况下,对应的组件是不重新渲染的。所以重复点击菜单不会改变路由,然后页面就无法刷新了。

解决方案: 借助重定向

利用一个空的 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>

2.挂载路由:src/router/index.js
在这里插入图片描述

{
   path: '/redirect',
   component: () => import('@/layout/components/redirect.vue')
 },

3.菜单跳转的地方添加事件,进行相关处理:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

<el-menu ... @select="selectMenuItem">
    // ...
</el-menu>
methods: {
    selectMenuItem(url, indexPath) {
      // console.log('点击菜单刷新当前页面')
      // console.log(url, indexPath)
      // console.log(this.$route.fullPath)
      if (this.$route.fullPath === url) {
        // console.log('点击的是当前路由 手动重定向页面到')
        // 点击的是当前路由 手动重定向页面到 '/redirect' 页面
        this.$router.replace({
          path: '/redirect',
          query: {
            path: encodeURI(url)
          }
        })
      }
    }
  }

用此种方法,能实现真正的页面(组件)刷新,当点击同一菜单时,地址栏每次的变化都是从:http://localhost:8080/#/redirect?path=xxxxxx 至 http://localhost:8080/#/xxxxxx

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值