How to replace one parameter in Vuejs router

Dav*_*ans 6 vue.js vue-router

We have a multi-level multi-tenant application, where the hostname identifies the 'supplier' account, but the customer account is actually part of the URL.

For instance, we have routes set up as follows:

/:locale/app/:customer_id/invoices
Run Code Online (Sandbox Code Playgroud)

At the top of the page, we have a drop down with all customer ID's the user has access to. The idea basically is that when a user changes the customer, the route changes from /nl/app/4/invoices to /nl/app/5/invoicesfor instance. So basically what I want to do is tell VueJs router to take the current route, and just change one parameter value in that route.

As you can imagine: the same goes for the :locale parameter where we basically have a language switch on top.

I know you can use $router.push in combination with a named route, and pass the current params in, replacing the params I want to update, but that would mean I'd have to name every route, and I'd need to know what the routes name is when I do an update.

有没有办法只要求 VueJS 路由器“给我当前路由”,然后更新一个参数?

我在 SO 以及其他资源上搜索了很多,但到目前为止没有得到一个好的结果......

Har*_*til 10

您实际上不需要为此功能命名路由或手动创建路径。路由器pushreplace方法支持部分补丁。您可以构建一个简单的可重用函数来实现此目的:

// This function expects router instance and params object to change
function updatePathParams($router, newParams) {

  // Retrieve current params
  const currentParams = $router.currentRoute.params;

  // Create new params object
  const mergedParams = { ...currentParams, newParams };

  // When router is not supplied path or name,
  // it simply tries to update current route with new params or query
  // Almost everything is optional.
  $router.push({ params: mergedParams });
}
Run Code Online (Sandbox Code Playgroud)

在您的组件中,您可以像这样使用它:

onClickHandler() {
  updatePathParams(ths.$router, { locale: 'en-us' });

  // Sometime later
  updatePathParams(ths.$router, { customer_id: 123 });
}
Run Code Online (Sandbox Code Playgroud)

另外,在这里我将 params 对象与现有值合并来说明这个想法。实际上,您不需要传递所有params。如果您只想更改一个参数,例如customer_id,,那么只需执行:$router.push({ params: { customer_id: 1234 } })。Vue-router 足够聪明,可以保留相同的路由并保持其他参数(locale此处)不变。