Vue-router: replace option is missing when use beforeEach hook

Created on 11 Jan 2017  路  13Comments  路  Source: vuejs/vue-router

The route object doesnot contain any replace imformation, so if i call router.replace() or enable replace in <view-link replace>, then use next(path) always invoke history.push

Most helpful comment

I need every route contain the same query info, but do not want to copy it in every navigation, in beforeEach hook, just add it if not provided, so i need the next(path) in the hook keep the same behavior

All 13 comments

It's added in 2.1.0 https://github.com/vuejs/vue-router/releases/tag/v2.1.0

router.beforeEach((to, from, next) => {
  if (to.path === '/foo') {
    next({
      path: '/bar',
      replace: true
    })
  }
})

You are not get it, I do not know the navigation which invoke beforeEach hook is push or replace

Yes, there's currently no information about whether beforeEach was invoked by push/replace.
Can you explain why you need it?

I need every route contain the same query info, but do not want to copy it in every navigation, in beforeEach hook, just add it if not provided, so i need the next(path) in the hook keep the same behavior

In this case where you want to enforce query params, simply call next again with replace: true

router.beforeEach((to, from, next) => {
    next()
    next({
        query: {
            foo: 'bar'
        },
        replace: true
    });
});

I need the same help. Please open this.

1620

+1 for this feature.

I want to hook the router in each page in ddtalk app, to add parameter dd_nav_bgcolor, but I found all the links in next are set as router.push...

router.beforeEach ((to, from, next)=> {
    if (to && to.query && !to.query.dd_nav_bgcolor)
    {
        to.query.dd_nav_bgcolor = 'FF08B2F2';
        next(to);
    }
    else
    {
        next();
    }
  });

+1

+1

The same question!

router.beforeEach((to, from, next) => {
  if (to.query.r) {
    next()
  } else {
    next({
      // replace: true,
      path: to.path,
      query: Object.assign(to.query, { r: Math.random() })
    });
  }
})

+1

the query is not modifiable, create a new object:

query: Object.assign({}, to.query, { r: Math.random() })
// or
query: { ...to.query, r: Math.random() }

Closing to prevent noise from questions

Was this page helpful?
0 / 5 - 0 ratings