wittgenstein
wittgenstein

Reputation: 4500

prevent vue-router to open same path

can you give me some feedback about my solution?

I want to prevent vue router to open a site the user sees already.

The problem was: the user had open a site with a double id as paramters like this: path: '/detail/:idType/:itemId After a click on the same tab again the last id /:itemId was removed in the url and the user sees a different view, which I want to prevent.

My current solution is adding a navigation guard:

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

Is it okay to return if the names matches? Do I use the correct router method?

thanks!


Edit for 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'" 
/>

Upvotes: 2

Views: 1243

Answers (1)

tao
tao

Reputation: 90287

To abort a navigation, call next(false) (in your case: if (to.name === from.name) next(false))

To allow it to pass (to its target), call next with undefined: next() (or next(undefined) - if you want to write more explicit code)

And to redirect it, call next with an object containing either name or path (i.e: next({ name: 'Login' }))

Upvotes: 4

Related Questions