Utilizing asynchronous components within a Vue.js component using an Axios request

I am currently developing a small application using VueJS, and I have an API that provides information about the components needed for rendering the page.

The setup of vue-router looks like this:

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

export const router = new VueRouter({
    routes:
        [
            {
                path: '/',
                component: Vue.component('welcome', () => import('../Components/Admin/Login.vue')),
                name: 'login'
            },
            {
                path: '/:page',
                component: Vue.component('dashboard', () => import('../Components/Admin/Dashboard/Dashboard.vue')),
                name: 'dashboard'
            },

        ]
});

The dashboard component in turn asynchronously loads the required components as shown below:

<template>
    <div>
        <header>
           // Header content
        </header>

        <div class="section" id="dashboard">
            <div class="columns">
                <aside class="column is-2 menu-section">
                    <nav class="menu is-centered">
                        // Menu section
                    </nav>
                </aside>

                <main class="column" id="main-section">
                    <page-title :title="title"></page-title>

                    <div class="columns is-multiline">
                        <div class="column">
                            <top-seller-widget></top-seller-widget>
                        </div>

                </main>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: "dashboard",
        data() {
            return {
                pageComponents: '',
                title: '',
                description: ''
            }
        },
        components: {
            'PageTitle': () => import('./PageTitle'),
            'TopSellerWidget': () => import('./TopSellerWidget')
        },
        created() {
            axios.get('/api/page-components?slug='+this.$route.params.page).then(response => {
                if(response.status === 200)
                {
                    this.title = response.data.page.title
                    console.log(response.data)
                }
            })
        }
    }
</script>

<style scoped>
    // Some styling
</style>

The issue arises when trying to dynamically load components based on the API response. Although individually importing components worked fine, creating a dynamic loop caused errors as shown below:

axios.get('/api/page-components?slug='+this.$route.params.page).then(response => {
    if(response.status === 200)
    {
        this.title = response.data.page.title
        if(response.data.page.content)
        {
            response.data.page.content.components.forEach(function (val, index) {
                Vue.component(val.name, () => import(val.location))
            })

        }
        console.log(response.data)
    }
})

These errors led to troubleshooting steps which can be seen here:

https://i.sstatic.net/gIcS6.png

Console output also indicated issues:

https://i.sstatic.net/Yc6v6.png

Any advice on how to handle such scenarios efficiently?

Answer №1

It seems like you are on the right track to finding the solution yourself. The error log is indicating that import(val.location) is trying to import a dependency as an expression, which is causing the issue. You should replace it with a specific name, just like you did in your test.

Additionally, it may not be necessary to asynchronously load both components (PageTitle and TopSellerWidget) within Dashboard. Since Dashboard itself loads asynchronously, any of its dependencies like PageTitle will also be loaded when Dashboard is requested. Since both PageTitle and TopSellerWidget are essential for rendering Dashboard, it might be more efficient to fetch them together with Dashboard instead of making an additional request.

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

Defining the scope of a variable that is accessed by multiple asynchronous callbacks

Utilizing the async.js library by Caolan McMahon and the jQueryUI progress bar, I am providing real-time feedback to users while multiple asynchronous calls gather data and populate elements in a complex graph. The lingering question is: What is the most ...

Error with the setInterval() method, function is not executing

UPDATED CODE SNIPPET: <script> $.ajaxSetup({ cache : false }); function fetchMessage() { $.get("php/getMessage.php?q=1" + "&" + Date.now(), function(data) { $("#typed").typed({ ...

Use Vue.js to shorten the number of decimal places and include commas in numerical values

How can I best parse a long number retrieved from a JSON using VueJS within a for loop? The JSON data is used in a v-for prop to create Li elements for a side navigation. I attempted to use vue-numeric without success since the project does not utilize ECM ...

Submitting HTML forms in SilverStripe using Ajax

I need to transfer data from a basic HTML form to a controller using Ajax, then handle the data and send a response back. Currently, my setup looks like this: HomePage.ss <form method="POST" class="form-horizontal submit-form" onsubmit="return checkf ...

What are some key indicators in the source code that differentiate TypeScript from JavaScript?

Reviewing some code on Github, I am looking for ways to quickly determine whether the script is written in JavaScript or TypeScript. Are there any simple tips or hints that can help with this? For instance, when examining an array declaration like the on ...

Display a message if the local storage is empty

Recently, I came across a javascript code snippet that is designed to save birthday data in local storage and then display the data within a div element. The current functionality only shows nothing if the storage is empty. However, I require it to display ...

Executing a Sequence of SQL Queries in Node.js

I am facing the challenge of performing nested queries to retrieve values from the database in order to generate a chart. The current approach involves executing a total of 12 queries, each aggregating the number of customers for every month of the year. ...

NuxtJs suddenly decided to call it quits, throwing fs errors left and right

As I was diligently working on my NuxtJS SPA, I suddenly encountered a series of errors after refreshing the page. To my surprise, I hadn't made any changes that could have caused this issue. Despite trying everything from npm fixes to reinstalling th ...

Optimal method for efficiently loading a JSON file over 100MB in Node.js

Each day, my system generates data and stores it in a json file that is around 120MB in size. I'm currently working on sending this data to the client using nodejs. router.get('/getData',(req, res) => { const newData = require(`./ne ...

Creating a clickable link using a JavaScript array and displaying an image source in a React component

I am currently working on a React component that is responsible for mapping data from a .js file, which contains objects in an array. I am facing difficulties in linking my title and images from within this function to access respective pages. Within this ...

Import reactjs modules without the need for Browserify, Webpack, or Babel

I am attempting to set up a TypeScript HTML application in Visual Studio. My goal is to incorporate reactjs v0.14.7 without relying on tools like Browserify. But, how can I utilize the react-dom module in this scenario? Let's set aside TypeScript fo ...

ReactJS - When a child component's onClick event triggers a parent method, the scope of the parent method may not behave as anticipated

In my current setup, I have a parent component and a child component. The parent component contains a method within its class that needs to be triggered when the child component is clicked. This particular method is responsible for updating the store. Howe ...

The scroll event is triggered only when scrolling upwards

I am encountering an issue with my scroll function. Currently, it only alerts when scrolling to the top instead of the bottom. How can I correct this so that it triggers the alert when reaching the bottom of the page? $(window).scroll(function() { if ...

Stopping prior entries in html tables

Is there a way to change the color of samples by clicking on each cell? Additionally, is it possible to cancel previous input by clicking a cancel button? If anyone has experience with this issue, please share your knowledge. Thank you. $(function() { ...

The SourceMap in DevTools encountered a parsing error with the message: "chrome-extension

It's been about a week since I first noticed warning messages appearing in my Google Chrome console. https://i.sstatic.net/Aurgz.png Clearing the cache hasn't made a difference; the messages only vanish when in incognito mode. Any suggestio ...

Retrieving data from Node.js within an Angular application

I am currently working on retrieving data from MongoDB and displaying it on my website. However, I am facing an issue in sending the entire fetched object to a specific port (the response) so that I can retrieve it from Angular. I also need to know how to ...

Exploring the process of creating a interactive rectangular border on an image with JavaScript

I'm currently working on a project that requires me to draw multiple bounding boxes interactively within an image displayed on a web browser. After drawing the bounding boxes, I will need to extract their coordinates. Are there any suggestions for a J ...

How to activate Yii2 confirmation popup

I have a special ActionColumn on my GridView and I'm attempting to use the yii.confirm function with the data-confirm attribute for the delete action, but the dialog box is not appearing. [ 'format'=>'html', 'content' ...

Restrict OrbitControls to a specific region of the page that is separate from the rendering area

As an experienced COBOL programmer delving into the world of Javascript and Three.js for a personal project, I've been grappling with a particular question for the past couple of days. Despite scouring StackOverflow for answers related to OrbitControl ...

What is the best method for updating inner html with AJAX using the results obtained from json_encode?

If you need further clarification on how this works, feel free to check out this fiddle for a demonstration. In my setup, I have multiple DIVs each with a unique ID such as desk_85 (the number changes accordingly). <div class="desk_box_ver id="desk_8 ...