Achieve compatibility for two different types of route parameters in Vue.js

I am trying to set up nested sets of categories in URLs that lead to specific products, but I'm having trouble with matching the routes correctly.

Here are the URLs I want:

--- renders a "category.show.vue": /$categorySlug+
app.com/catA/catB/
app.com/catA/catB/catXXX

--- renders a "product.show.vue": /$categorySlug+/$id-$productSlug
app.com/catA/111-nvidia-rtx-3080ti
app.com/catA/catB/222-nvidia-rtx-2060
app.com/catC/catD/333-iphone-13-pro

I have attempted this, but it's giving me errors:

{
  path: '/:slug(\\w+)+/:productSlug(\\d+)',
  name: 'product.show',
  props: route => ({ slug: route.params.slug }),
  component: () => import('pages/product.show.vue')
},
{
  path: '/:slug+',
  name: 'category.show',
  props: route => ({ slug: route.params.slug }),
  component: () => import('pages/category.show.vue')
}

Is there a way to make these routes work together?

Answer №1

The regular expression pattern in :productSlug(\\d+) (specifically, \d+) only matches digits, however, your product URLs contain more than just digits (for example, one of them ends with /111-nvidia-rtx-3080ti), resulting in no match. The parameter's pattern must be an exact match.

To fix this issue, include a wildcard matcher in the productSlug pattern:

// BEFORE
// :productSlug(\\d+)

// AFTER
:productSlug(\\d+.+)
                 ^^ one or more characters, matching anything

Additionally, since it appears that each URL contains only one product, the route parameter pattern should not be suffixed with +:

// BEFORE
// :productSlug(⋯)+

// AFTER
:productSlug(⋯)

The updated route path for product.show should be:

path: '/:slug(\\w+)+/:productSlug(\\d+.+)',

demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determining if a swf file has loaded using JavaScript and swfobject

Here is the code snippet I am working with: <head> # load js <script> function graph() { swfobject.embedSWF( "open-flash-chart.swf", "chart", "400", "180", "9.0.0", "expressInstall.swf", {"data-file":"{% url moni ...

What could be the reason for my ajax request coming back with no data?

When I make this ajax request: $.ajax({ type: "POST", url: "/admin/RoutingIndicators/Add", data: { newSecondaryRI: newRi }, success: function () { alert('hit'); document.location.reload(true); }, error: fu ...

The Glyphicon icon fails to appear on the initial page load and only shows up after refreshing the

I have been utilizing bootstrap.min.css from bootstrap v3.3.5 which I downloaded from http://getbootstrap.com and used it locally. However, I encountered an issue with glyphicons when running it on IE 9 and above. The glyphicon icon disappears on the first ...

Dynamic Images with Next.js

Currently, I am utilizing next.js and attempting to dynamically retrieve images in the following manner: {list.map((prod) => ( <div className={styles.singleProduct}> <h6>{prod.Brand.toUpperCase()}</h6> <p&g ...

Error message indicating that `vue-loader` could not be located when attempting to run `npm run

I keep encountering an issue when trying to run npm run dev. I'm getting the following error and have no idea how to resolve it. I've tried reinstalling Node.js to the latest version and reinstalling all packages via the command line: [webpack-cl ...

Obtaining Data from an XML Node Using AJAX

Trying to extract statistics from my XML based on a specific name request, but encountering issues with my JavaScript functionality. XML data: <player> <forward><name>Joe</name><stats>45</stats></forward> <f ...

Why is it important to avoid reassigning parameters in real-life situations? Can you provide an example of a problem that may arise from this practice?

Many inquiries focus on the best methods to follow the no-param-reassign linting rule, but there is a lack of requests to demonstrate the reasoning behind the rule. It is common to hear claims like 'Assigning values to variables defined as function p ...

Achieve the effect of "background-attachment: fixed" using a div element

I am attempting to replicate a similar effect as seen here, which is accomplished using the CSS property background-attachment:fixed. However, I want to achieve this effect using div elements instead. For instance, could I apply this effect to an h1 tag? ...

The HTML function transforms blank spaces into the symbol "+"

Just starting out with a question: I created a basic submission form, but I noticed that if there are any spaces in the inputs, the values get changed to a plus sign (+). Here's my form: <form name="input" action="search" method="get"> Web Ad ...

What steps should I take to create an object that can be converted into a JSON schema like the one shown here?

I'm facing a rather simple issue, but I believe there's something crucial that I'm overlooking. My objective is to iterate through and add elements to an object in order to generate a JSON structure similar to the following: { "user1": ...

Determine the value of an object by iterating through its keys

UPDATE: (for clarification) I currently have a table named modelCoa +----+----------+-------+--------------------+ | id | id_parent| code | name | +----+----------+-------+--------------------+ | 1 | 0 | 1 | asset ...

Speed up - Handle alias resolution with module federation

Currently import federation from '@originjs/vite-plugin-federation'; import react from '@vitejs/plugin-react-swc'; import dns from 'dns'; import path from 'path'; import { visualizer } from 'rollup-plugin-visual ...

React Hooks: Issue with UseRef not detecting events from Material UI Select component

I'm currently utilizing React Hooks in my project. I am attempting to trigger an onclick event using the useRef hook. const component1: React.FC<Props> = props { const node =useRef<HTMLDivElement>(null); const ClickListe ...

What are some effective strategies for avoiding the issue of a hook being invoked multiple times?

Having an issue with my vue3 project. Essentially, I need to handle different layouts for various scenarios such as authorization, user profiles, and group layouts. Here's my approach: Create a component AppLayout.vue to manage layouts <template& ...

What is the most efficient method for retrieving an element using a data attribute with an object (JSON) value?

Imagine having the following HTML element: <div class='element' data-info='{"id":789, "value":"example"}'></div> By running this JavaScript code, you can access the object stored in the data attribute. console.log($(&apos ...

Having trouble accessing the property '_wrapper' of an undefined object when using vue multiselect

Encountering an issue with VUE-MULTISELECT Here is the code snippet: <b-modal id="skills"> <div> <label class="typo__label">Tagging</label> <multiselect v-model=&q ...

Leveraging AngularJS ngBind with a JavaScript object

Within the given string, integrating a javascript object and embedding it into an ngBinding does not result in proper evaluation. I have a string where I want to incorporate a specific part of a javascript object and am transitioning to Angular for its use ...

Convert Python strings into HTML JavaScript blocks using Jinja2

Having trouble passing a string to an HTML page in the "<script>" block. I am currently using Python, Flask, and Jinja2. Python code: def foo(): return myString #"[{title: 'Treino 7-Corrida',start: '2015-12-08',color: '#d ...

Using JavaScript, append a hidden input field in Yii2 and retrieve it from the controller

Seeking assistance as a newcomer to yii2. I'm looking for help in resolving an issue that has arisen. I'm attempting to add a hidden input field to my form using JavaScript (not linked to a model). Subsequently, when I submit the form, I want to ...

Guide on utilizing automatic intellisense in a standard TextArea within a web application

I have successfully created an Online compiler web application that is currently running smoothly. However, I am now looking to enhance my application by implementing intellisense in the TextArea where the program is being typed. For instance, if I type "S ...