Issue with Vue Router not rendering components after dynamically importing them

I am facing an issue with vue-router while trying to register components dynamically. When I use hardcoded code, the router functions properly. However, when I load my routes dynamically, it fails to render the component.

The component file is being imported dynamically:

GetAllPages((data) => {
    let pages = [];
    data.map(page => {
        const pageTitle = page.title.rendered.toLowerCase();
        import(`../pages/${pageTitle}.js`).then(module => {
            pages.push({
                path: `/${pageTitle}`,
                name: `${pageTitle}`,
                component: module.default
            })
        })
    })
    return pages;
})

Here is the router function:

new VueRouter({
    mode: 'history',
    // routes: pages <= not registering data
    routes: [
        {path: '/about', component: About} // <= working fine
    ]
});

The dynamically imported file looks like this:

let AboutPage = {
    data: () => ({
        Message: "hey"
    }),
    render: () => {
        return "<h1>{{Message}}</h1>";
    }
}

export default Vue.component("About", {
    data: AboutPage.data,
    template: AboutPage.render()
})

The issue lies in the fact that while hardcoded routes work, dynamically imported pages do not. Even if I manually define the imports within the data.map function, the page does not render. Strangely, there are no errors displayed by the router in the console.

Note: If I log the router instance, I can see that the dynamically imported routes are set, but they are not rendering HTML.

Answer №1

You have a couple of options to consider...

  1. Delay the creation of your router until all imports are resolved. This would mean being able to defer the initialization of your root Vue instance.
  2. Utilize lazy-loaded components for creating your router.

Personally, I suggest going with option #2

new VueRouter({
  mode: 'history',
  routes: data.map(page => { // data obtained from GetAllPages function
    const pageTitle = page.title.rendered.toLowerCase()
    return {
      path: `/${pageTitle}`,
      name: pageTitle,
      component: () => import(`../pages/${pageTitle}.js`)
    }
  })
});

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

``Incorporating Vuetify components into VueJs components dynamically: A step-by-step guide

I have some data that includes HTML elements: data(){ text: 'Go to <v-btn> to="profile">Profile</v-btn>'} Now I want to render this data with the embedded HTML in my component. I attempted to accomplish this using th ...

Performing an AJAX request to the database when a change occurs, prior to submitting the

In my user setup/create form, I am including a field for the users' license/certification number which needs to be validated and returned to a specific DIV Onchange before the form is submitted. I have heard that using AJAX POST is the way to achieve ...

When attempting to run HTML and JavaScript files locally, an error is encountered: "TypeError: The module name 'openai' is not resolving to a valid URL."

As a beginner in web development, I decided to follow a tutorial on creating a web application using the OpenAI API. The tutorial instructor runs the code in an environment called Scrimba, but I am working on my MacBook. This is how the app functions: it ...

When using Vue computed, an error is thrown stating "Issue in rendering: 'InternalError: too much recursion'" if the same key is referenced in computed

As a newcomer to Vue, I wanted to track how many times a function in the computed section gets called. To achieve this, I created the following component: const ComputedCounter = { name: "ComputedCounter", template: ` <span>{{ value } ...

Fetch data for Chart.js tooltips dynamically

One common way to load information for a tooltip in a chart is by using the following code snippet: window.myLine = new Chart(chart, { type: 'line', data: lineChartData, options: { tooltips: { enabled: true, mode: 'sin ...

The Angular JS Root scope is modified after submitting a form

I'm new to Angular JS and I'm trying to figure out how to save an object into $rootScope in my application. However, when I try to make a post request without including the object from rootScope, it doesn't work as expected. Now, on a newly ...

How can I use Angular to automatically check a checkbox while a page is loading?

I have a list of checkboxes, and based on the selected checkbox, offers are displayed. Everything is working fine as expected. Below is the code snippet I have implemented: function Test1Controller($scope) { var serverData = ["Samsung Galaxy Note ...

Ensuring radio button validation prior to redirecting to contact form

I created a survey form using HTML and CSS. I am looking to add validation to the questions before redirecting to the Contact form page. Currently, when a user clicks on the submit button in the Survey form, the page redirects to the contact form. Howeve ...

fetching numerous JSON documents using jquery

I am struggling to retrieve data from multiple JSON files and display it in a table. Despite being successful in appending data from one JSON file, I encountered issues when trying to pull data from multiple files. Here is my code: var uri = 'sharepo ...

Guide on incorporating d3 axis labels within <a> elements?

Issue at Hand: I am working with a specific scale var y = d3.scalePoint().domain(['a','b','c']).range([0,100]); I have successfully created an axis for this scale var y_axis = svg.append("g").attr("class", "axis").call(d3. ...

Manipulating the DOM to show various elements upon clicking on text

Currently, I am engaged in a small project that involves experimenting with DOM manipulation. The project revolves around creating a Todo list where users can generate various categories (such as work, gym, finances, etc.) and then add corresponding subtas ...

Creating a <Box /> component in MaterialUI with styled components is a great way to customize the design and layout of your

@material-ui/styles offers a different way to customize default styles: import React from 'react'; import Box from '@material-ui/core/Box'; import { styled } from '@material-ui/core/styles'; const StyledBox = styled(Box)({ ...

Enhancing user experience by implementing AJAX in a contact form to eliminate the need for page

I have read numerous questions on this topic and have compiled the code I currently have from various responses. Unfortunately, despite my efforts, I am unable to make it work and I cannot identify the reason behind this issue. Below is the HTML form str ...

Python Selenium: Cannot Click on Element - Button Tag Not Located

TL,DR: My Selenium Python script seems to be having trouble "clicking" on the necessary buttons. Context: Hello. I am working on automating the process of logging into a website, navigating through dropdown menus, and downloading a spreadsheet. Despite ...

"Error in react-three-fiber: Only the last mesh retains its model, all others are

Currently, I am working on a React application where I am using react-three-fiber to visualize data in a 3D environment. My goal is to create various models by passing data representing their characteristics as props into components. However, I am encounte ...

Preserve the specific date and time in the designated timezone

Utilizing the react-datePicker library requires using new Date() as input. I need to save the user's selected date, time, and timezone in such a way that regardless of their location, they will see Feb 10 2024 02:00 BST in the Date Object. Currently, ...

Event delegation will be ineffective when the target element is nested within another element

After receiving a recommendation from my colleagues on Stackoverflow (mplungjan, Michel), I implemented the event delegation pattern for a comment list. It has been working well and I am quite excited about this approach. However, I have encountered an iss ...

What is the best way to create an image carousel that continuously loops instead of resetting?

Currently tackling an issue with my image carousel project. The automatic function of the slider is not functioning as desired. Instead of looping back to the first image when it reaches the last one, it moves all the way back to the beginning, displaying ...

Update an existing item or add a new one if it is not already present

I am attempting to create a functionality similar to canva.com, where users can select images from the sidebar and drop them anywhere in the "div", allowing multiple images with individual positions. However, when I use setState(prevState=>{return [...p ...

Save JSON Tree data in the Database

Given a tree structure JSON, I am tasked with creating an API to insert all the data into a database at once. The organization entities can have multiple parents and children relationships. An example of the JSON data: { "org_name": "orga ...