防止 vue-router 打开相同的路径

prevent vue-router to open same path

你能给我一些关于我的解决方案的反馈吗?

我想阻止 vue router 打开用户已经看到的站点。

问题是:用户打开了一个带有双 ID 作为参数的站点,如下所示:path: '/detail/:idType/:itemId 再次单击同一选项卡后,最后一个 ID /:itemId 在 url 并且用户看到了不同的视图,我想阻止这种情况。

我目前的解决方案是添加 navigation guard:

// router.js
router.beforeEach((to, from, next) => {
    if (to.name === from.name) return
    else next()
})

如果名称匹配,return 可以吗? 我使用正确的路由器方法吗?

谢谢!


为 Praveen 编辑

// router.js
const router = new VueRouter({
    routes: [
        {
            path: '/new',
            name: 'New',
            component: () => import('../layout/New'),
            props: {
                mode: 'create'
            }
        },
        {
            path: '/edit/:uuid',
            name: 'Edit',
            component: () => import('../layout/New'),
            props: {
                mode: 'edit'
            }
        },
        {
            path: '/detail/:idType/:itemId/:uuidId?',
            name: 'Detail',
            component: () => import('../layout/Detail'),
            props: true,
        }
    ],
    mode: 'hash',
    linkActiveClass: 'active'
})
// tab navigation
<b-link
  :to="{ name: ['Edit', 'Detail'].indexOf($route.name) !== -1 ? $route.name : 'New'}"
  class="btn btn-site-nav"
  type="button" 
  v-text="'Booking'" 
/>

要中止导航,请调用 next(false)(在您的情况下:if (to.name === from.name) next(false)

为了让它通过(到它的目标),用 undefined 调用 nextnext()(或 next(undefined) - 如果你想写更明确的代码)

要重定向它,请使用包含 namepath 的对象调用 next(即:next({ name: 'Login' })