vue-router相同路径跳转页面刷新

495 阅读1分钟

以下内容仅用作个人工作总结学习

1. 问题

相同路径页面的跳转分两种情况

  • 路径完全相同,包括参数,eg:
/system/user?id=1  ->  /system/user?id=1
  • 路径path相同,参数不同,eg:
/system/user?id=1  ->  /system/user

2. 方案

  • 针对第一类问题,常用方式为:借用一个空组件,做跳转,代码如下
// router.ts
{
    path: "/refresh",
    name: "refresh",
    meta: { title: "刷新路由" },
    component: () => import("@/views/refresh/refresh.vue")
}

router.beforeEach((to, from, next) => {
    if (to.path === from.path) {
        next("/refresh")
    } else {
        next()
    }
})

// refresh.vue
<template></template>
<script>
export default {
    beforeRouteEnter(to, from, next) {
        next((vm) => {
            vm.$router.replace({ path: from.path, query: from.query })
        })
    }}
</script>
  • 针对第二类问题,一般有两种解决方案

a. 对于需要刷新的组件,使用beforeRouteUpdate或者watch监听路由,执行回调

b.在外部路由出口统一添加key,<router-view :key="$route.fullPath" />

// vue3监听路由
const router = useRouter()
watch(
    () => router.currentRoute.value,
    () => {
        // ...
    }
)

const route = useRoute()
watch(
    () => route,
    () => {
        // ...
    }
)