2

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'" 
/>
2
  • While the answer by @tao might work for you I wanna know what your router configuration looks like for the same. It may be that you aren't nesting your router views properly. Commented Feb 22, 2021 at 13:18
  • I have added the simplified configuration. What do you think about it? I don't use nested routes at all... Commented Feb 22, 2021 at 13:53

1 Answer 1

4

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' }))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.