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

标签 vue.js vuejs2 navigation vue-router

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

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

问题是:用户打开了一个具有双 ID 作为参数的网站,如下所示: path: '/detail/:idType/:itemId 最后一次单击同一选项卡后id /:itemId 已在网址中删除,用户会看到不同的 View ,这是我想要阻止的。

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

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

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

谢谢!


编辑 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 调用 next:next() (或 next(未定义) - 如果你想编写更明确的代码)

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

关于vue.js - 防止 vue-router 打开相同的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66315773/

相关文章:

javascript - 无法访问数据。对象在另一个对象中?

firebase - 在 Vuejs 中放置 firebase.auth().onAuthStateChanged() 的位置

使用 vue-router 登录后重定向到请求的页面

ios - 对于 iOS,有什么方法可以知道导航源?

css - 如何让我的 NAV 文本在悬停时停止移动?

javascript - 如何使用 VueJS 中的计算属性从 v-for 指令过滤器中删除重复?

vue.js - 使用 vuejs 更改输入类型?

javascript - 如何定义新路由器?

templates - Vue JS v-bind 图像 src 属性组合路径字符串与对象值不起作用

c# - 使 WPF 导航动态化 - 使用 XML 文件?