VueJS's approach to routing through modular components

I am currently working on a website where I need to set up different category pages using dynamic routes. To achieve this, I am utilizing vue-router and aiming for a single dynamic route that can switch between pages by loading different components.

Here are the specific routes I intend to implement:
example: '/shop/men' , '/shop/women','/shop/kids'

In my index.js file for the router, I have gender appended at the end of the route to determine which component should be loaded. However, I am encountering an issue in handling this aspect and dynamically loading the appropriate component based on it.
router-> index.js:

{
        name: 'shop',
        path: '/shop/:gender',
        component: menCategoryViewsHandler('mencategory')
}

views -> viewHandler -> mencategory.js:

'use strict'

import Handle from '../mencategory.vue'

const camelize = str => str.charAt(0).toUpperCase() + str.slice(1)

// This function serves as a factory for creating root-level views dynamically,
// as they share similar logic except for the item types they display.
// Essentially acting as higher order components wrapping respective Vue files.
export default function ViewsHandler (type) {
  console.log('1',type)
  return {
    name: `${type}-mencategory-view`,
    asyncData ({store, route}) {
      //@todo : add the ssr and routerbefore load change script here
      return Promise.resolve({})
    },
    title: camelize(type),
    render (h) {
      return h(Handle,
        {
          props: {type},
        },
      )
    },
  }
}

Answer №1

If you want to implement dynamic route matching in Vue.js, you can create a wrapper component that will render the appropriate Category component based on the route. This can be achieved by passing props to components.

// CategoryResolver.vue
import menCategory from './mencategory'
import womenCategory from './womencategory'
import kidsCategory from './kidscategory'

const components = {
  menCategory,
  womenCategory,
  kidsCategory
}
export default {
  functional: true,
  props: ['category'],
  render(h, ctx) {
    return h(`components[${category}Category`], ctx.data, ctx.children)
  }
}

To set up your router for this functionality:

const router = new VueRouter({
  routes: [
    { path: '/shop/:category', component: CategoryResolver, props: true  }
  ]
})

For example, if

menCategoryViewsHandler('mencategory')
returns a component called MenCat, it should have a prop named category which matches the route above. In MenCat, you would define:

export default {
    props: ['category'],
    ...
 }

The Vue router will automatically pass the URL parameter as a prop into your component.

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

Using async/await in a for loop | The await keyword can only be used inside an asynchronous function

I've been attempting to execute the following code: async function verifyExistingUsers(db, users) { return new Promise((resolve, reject) => { var companies = [] for (const [index, user] of users.entries()) { let comp ...

Utilizing Ajax to dynamically submit specific form fields

I'm just starting out with Jquery ajax, and I'm experimenting with submitting specific fields for validation instead of the entire form. I've created a function to check if a username is available, and it's working well. However, I want ...

Guide to adding content and icons to the top navbar on the right side using vue.js

In the process of developing a fixed top navbar, I encountered an issue while trying to add right side icons and additional content. The goal is to include two icons, as shown in this example: example link, along with profile and cart information on the ri ...

Quasar Framework Vue.js project experiencing unexpected disablement of console/debug output in PWA InjectManifest workbox

I recently added PWA capability to my project built with Vue.js / Quasar Framework. After changing the "workboxPluginMode" property to "InjectManifest", I noticed that Workbox was initially giving me debug information in the console as expected. Moreover, ...

What is the most efficient way to switch between different views in AngularJS while preserving the data in the views'

Every time I navigate from page1.html to page2.html in AngularJS and then return back to page1.html, my page model data disappears. Can someone please help me figure out how to preserve this data? I've looked at other questions on this topic but coul ...

Adding a # before each routing path: A step-by-step guide

One key difference between Angular 1 and Angular 4 is that in Angular 1, the routing path always includes a "#" symbol, whereas in Angular 4, it does not. I believe there may be a way to configure this function based on what I observed in the ng-bootstrap ...

Having trouble with router.push in Vue3 and Vuex4?

Encountering some issues with Vue 3 and Vuex. Attempting to redirect users when logged in within my Vuex file, but the redirection is not happening as expected. No errors are being returned, only a link change without actually redirecting to another page. ...

Error: The 'length' property cannot be searched for using the 'in' operator

Hmm, I keep getting an error that says "Uncaught TypeError: Cannot use 'in' operator to search for 'length' in" Every time I attempt a $.each on this JSON object: {"type":"Anuncio","textos":["Probando ...

Converting a JSON object into a format suitable for transmission through AJAX requests

I am attempting to transmit data in a JSobject via AJAX using jQuery. Below is the json object: var cookieData = { 'land' : document.URL, 'ref' : document.referrer }; The object is then stored in a cookie... throu ...

What is the best way to prevent the use of "******" at the beginning of every line in Javascript/Node Bund

Update: I am currently working on a Node.js test project (utilizing WebPack). In the development builds (app.js), at the start of each line, there is /******/ https://i.sstatic.net/jZ5h6.png Since this seems to be common behavior, I am wondering if th ...

Instantly summing up two numbers with javascript

In my web development work using Visual Studio 2008, I encountered an interesting challenge. On a webpage, I have three textboxes labeled "Price," "Quantity," and "Amount." The task at hand is to calculate the value of "Amount" by multiplying the values ...

Consecutive interdependent operations within a Vuex action

I'm currently working on a Vue application that is pulling data from the Contentful API. I have a thumbnail (image) field for each entry and I want to extract the main colors as hexadecimal values and store them in the state for use throughout the app ...

Ways to guarantee a distinct identifier for every object that derives from a prototype in JavaScript

My JavaScript constructor looks like this: var BaseThing = function() { this.id = generateGuid(); } When a new BaseThing is created, the ID is unique each time. var thingOne = new BaseThing(); var thingTwo = new BaseThing(); console.log(thingOne.id == ...

Receiving 'Unexpected end of input' error when using a string as a JavaScript function argument

I am trying to implement an ajax request function in my project. This is the code snippet I have: function Reject(id, scomment) { jQuery.ajax({ type: "POST", url: "reject.php", data: {id: id, Scomment: scom ...

Switching class upon clicking in Vue3

I'm trying to toggle a class on click, but for some reason it's not working as expected. <script setup> import { ref } from "vue"; let isOpen = ref(false); const toggleClass = () => { isOpen = !isOpen; console.log(isOpen) ...

How can a HTML element be clicked in JQuery to copy it into a text area?

Is it possible to select text from a list and insert it into a text box by clicking on it? I have developed a JSON API that retrieves a list of individuals from the database. Following this, there is a form with a text field that displays the list of peopl ...

When dalekjs attempted to follow a hyperlink with text in it, the link failed to function properly

My goal is to retrieve an element from a list by clicking on a link containing specific text. Here is the HTML code snippet: <table> <td> <tr><a href='...'>I need help</a></tr> <tr><a href=&a ...

What is the best way to automatically set today's date as the default in a datepicker using jQuery

Currently utilizing the jQuery datepicker from (http://keith-wood.name/datepick.html), I am seeking to customize the calendar to display a specific date that I select as today's date, rather than automatically defaulting to the system date. Is there a ...

How can I extract a list of errors from this JSON object in a React.js application?

Is there a way to extract the list of errors from the following JSON object using React js? data = { "container_1587015390439_0001_01_000004": { "ERROR":["20/04/16 05:43:51 ERROR CoarseGrainedExecutorBackend: RECEIVED SIGNAL TERM"] , ...

Tips for displaying text within an input field labeled "password" and then reverting back to a password display after entering text

I am working with a login form that includes a password field: <input type="password" name="password" id="password" value="Password" maxlength="40" required style="width: 130px; font-size: 10px;" /> Currently, the password field displays "******** ...