Learn how to dynamically import and load components in VueJS while rendering a list

I am currently rendering a list.

<div v-for="msg in messages">
   <div v-if="msg.type==='component'">
      <component v-bind:is="getComponent(msg.component)" :data="msg.data" :text="msg.text"></component>
   </div>
</div>

While I can successfully import and load a component using a computed property with a hardcoded name, I face difficulty in passing a parameter into a computed property.

Attempting to call a method instead results in an infinite loop causing the browser to crash.

   //This works as a computed property
   getComponent() { 
      return () => import(`@/components/data/finance/GRNISummary.vue`)
   },


   //This does not work as a computed property. Computed properties cannot accept parameters
   getComponent(component) { 
      const componentsList = {
        jurisdictionEvidenceCount: '/chart/export_control/JurisdictionEvidenceCount.vue',
        grniSummary: '/data/finance/GRNISummary.vue'
      }
      return () => import(`@/components` + componentsList[component])
   },


   //This method crashes the browser with an infinite loop of component loads 
   getComponent(component) { 
      const componentsList = {
        jurisdictionEvidenceCount: '/chart/export_control/JurisdictionEvidenceCount.vue',
        grniSummary: '/data/finance/GRNISummary.vue'
      }
      return () => import(`@/components` + componentsList[component])
  },

Answer №1

Dynamic imports utilize the Promise method internally, while the computed property requires a factory function — meaning it does indeed accept parameters as a function. However, in order for this to properly function, using require is recommended.

computed: {
  getComponent() {
    const componentsList = {
      jurisdictionEvidenceCount: '/chart/export_control/JurisdictionEvidenceCount.vue',
      grniSummary: '/data/finance/GRNISummary.vue'
    }

    return component => require(`@/components` + componentsList[component]);
  }
}

By the way, if you've included vue in the resolve.extensions, you can omit the extension type when importing a component. (Vue CLI should handle this by default). Alternatively, you can verify this by running:

vue inspect resolve.extensions

Here are my proposed revisions:

computed: {
  getComponent() {
    // It may be beneficial to relocate this section
    const componentsList = {
      jurisdictionEvidenceCount: 'chart/export_control/JurisdictionEvidenceCount',
      grniSummary: 'data/finance/GRNISummary'
    }

    return componentName => require(`@/components/${componentsList[componentName]}`);
  }
}

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

Integrate the dForm plugin with a convenient time picker widget

Currently, I am attempting to integrate a time picker widget into a jQuery plugin called dForm. The specific timepicker widget can be found at the following link: https://github.com/jonthornton/jquery-timepicker Despite reviewing the dForm documentation, ...

Tips for successfully including a forward slash in a URL query string

My query involves passing a URL in the following format: URL = canada/ontario/shop6 However, when I access this parameter from the query string, it only displays "canada" and discards the rest of the data after the first forward slash. Is there a way to ...

User creation causing redirection malfunction

Recently, while working on a website, I encountered an issue with the registration process for users. It was functioning properly when I tested it a few days ago. After making some updates to other aspects of the website such as the login and profile sect ...

Obtaining the source code from a different domain website with the help of jQuery

Is there a way to extract part of the source code from a YouTube page without using server-side programming? I've tried cross-domain AJAX techniques like Yahoo YQL and JsonP. While Yahoo YQL allows me to grab part of the source code, I'm facing ...

Send all of the elements within an array as arguments to a function

My challenge involves working with an array of values: ['a', 'b', 'c', 'd'] I must pass these values as parameters to a function like this: window.myFunction('a', 'b', 'c', 'd&ap ...

Having trouble retrieving the HTML content after deploying my application on Heroku

I encountered an issue with my index.js file in Express Node.js once I deployed the app on Heroku. In production, I'm getting an error that seems to indicate that the server is unable to find my index.html file. *-src ---index.html ---index.js http ...

What is the best way to merge two tables together using the server-side JQuery Datatable plugin?

I recently came across an amazing example of a server-side ColdFusion jQuery datatable on this website: Check it out here However, I am facing an issue with adding a second table in the lookup. Specifically, while the primary table lists location_id, I al ...

Retrieve the present time of an ongoing CSS3 animation

I've been trying to retrieve the current time of a running animation, but I haven't had any luck so far. I can easily grab the start time using: myelement.addEventListener('webkitAnimationStart', function (evt){ console.log(evt.elaps ...

"Embed" three.js within SmartMS

Is it possible to incorporate this simple three.js example into Smart Mobile Studio without extensive wrapping? I attempted to copy the window.onload content into an asm section but was unsuccessful. <!DOCTYPE html> <html> <head> <t ...

What is the best way to display a Markdown field in Vue3?

After following the Nova documentation, I successfully linked a Markdown field to a TEXT database type: Markdown::make('Content', 'content_text') Now, I am trying to display it correctly on my web application: https://i.sstatic.net/E8 ...

Could not locate module: The package path ./react is not exported from the package in E:NextAppportfolio_website-mainportfolio_website-main ode_modules ext-auth

I am encountering an issue while trying to import SessionProvider from Next-Auth. The error message that is being displayed is: "Module not found: Package path ./react is not exported from package E:\NextApp\portfolio_website-main\port ...

Issue with iframe's size not displaying correctly

<body> <script> document.write("<iframe id='theframe' src='http://www.website.com?testvr=" + testvr + " height='900' width='500'></iframe>"); </script> </body> The iframe is added, but ...

Tips on implementing a Javascript function triggered by a user's click within the video player frame

<script> function greet() { alert("hello"); } </script> <iframe width="100%" height="315" src="https://www.youtube.com/embed/AGM0ibP1MRc" onclick="greet()"></iframe> .Kindly assist me, please. ...

Enable the input field once the checkbox has been marked

Here is a checkbox example: <div class="form-group"> <input type="checkbox" id="examination" class="form-control" name="exam" placeholder="Enter Title"> <label>Enable Exam</label> </div> Additionally, I have a disabled inpu ...

Can anyone help me get my carousel to work properly?

I am facing a carousel problem in my personal exercise project. I have gathered HTML, CSS, and JavaScript from the internet and am attempting to integrate them all together. //Sidebar script start $(document).ready(function () { var trigger = $(&apo ...

Top-notch java tool for caching and minifying dojo, jquery JavaScript, and CSS files

In our project, we have downloaded the Dojo and jQuery libraries from Google CDNs. I am currently seeking a Java tool that can both cache and minify these libraries. The caching process should take place within the ROOT project of Tomcat. While I am awar ...

Troubleshooting: JSColor Is Failing to Function Properly in Volusion's

Recently, I've encountered some issues with the JSColor plugin () on the Volusion e-commerce platform. Despite having successfully used it before, getting it to load correctly seems to be a challenge. My current task involves working on a test produc ...

Enhance and Modify feature using Javascript

I'm facing two issues with my product information form. Firstly, after I submit the data, I want the input fields to be cleared automatically. Secondly, the edit function doesn't seem to work at all. I'm quite stuck on how to resolve these p ...

Exploring the Power of Streams in JavaScript

I'm looking to create a stream object that can perform the following actions: // a -------1------2----3 // map -----\------\----\ // b --------2------4----6 const a = new Stream(); const b = a.map(value => value * 2); b.subscribe( ...

How can we implement a select-all and deselect-all feature in Vue Element UI for a multi-select with filtering capability?

As a newcomer to VueJs, I am exploring how to create a component that enables multiple selection with a search option and the ability to select all or deselect all options. To achieve this functionality, I am utilizing the vue-element-ui library. You can ...