Home  >  Q&A  >  body text

Set default values ​​for optional URL parameters in Vue Router while having independent optional URL parameters.

<p>I have the following route</p> <pre class="brush:php;toolbar:false;">export const personRoutes: RouteRecordRaw[] = [ { path: '/person/:id?/:handedSlug?', name: 'Person', component: () => import('./view/person'), }, ];</pre> <p>I have a method that accepts filter conditions and updates the route: </p> <pre class="brush:php;toolbar:false;">updateRoute(): void { const filters = this.filters; const router = this.$router; router.push({ name: 'Person', params: { id: filters.getId(), handedSlug: filters.handedSlug(), }, }); },</pre> <p>The problem I encountered is that if the id is null and handed is set, the returned URL is: person/handedValue, and what I need is person/all/handedValue. <br /><br />If the following parameters in the URL are set, how to set default values ​​for optional parameters? </p><p><br /></p>
P粉377412096P粉377412096413 days ago498

reply all(1)I'll reply

  • P粉785905797

    P粉7859057972023-08-04 12:52:00

    I don't think there is currently such a way, but if there is, it cannot be considered optional. I recommend simply passing in the string 'all' if filters.getId() is empty.

    updateRoute(): void {
      const filters = this.filters;
      const router = this.$router;
    
      let routeId = filters.getId()
      if (!routeId && filters.handedSlug()) {
        routeId = 'all'
      }
    
      router.push({
        name: 'Person',
        params: {
          id: routeId,
          handedSlug: filters.handedSlug(),
        },
      });
    }, 

    reply
    0
  • Cancelreply