dynamically import a variety of components in vue.js and nuxt depending on certain conditions

Is there a way to implement dynamic imports for all 3 components in this scenario? Each component has different props, so using the switch option in the computed method is not feasible.

I have come across solutions for using a single component dynamically, but I haven't found an example where multiple components can be imported based on conditions. While inspecting the UI, it appears that my component is not being loaded due to the v-if condition. However, checking the Network tab reveals that the component is actually imported.

Here is the template:

<template>
   <div>
      <b-button v-if="condition1" v-b-toggle.collapse-1 variant="primary">Component1</b-button>
      <b-collapse id="collapse-1" class="mt-2">
         <b-card>
            <p class="card-text">Collapse contents Here</p>
            <component :is="condition1" :data1 = "data.cond1" />
         </b-card>
      </b-collapse>
      <b-button v-if="condition2" v-b-toggle.collapse-2 variant="primary">Component2</b-button>
      <b-collapse id="collapse-2" class="mt-2">
         <b-card>
            <p class="card-text">Collapse contents Here</p>
            <component :is="condition2" :data2 = "data.cond2" />
         </b-card>
      </b-collapse>
      <b-button v-if="condition3" v-b-toggle.collapse-3 variant="primary">Component3</b-button>
      <b-collapse id="collapse-3" class="mt-2">
         <b-card>
            <p class="card-text">Collapse contents Here</p>
            <component :is="condition3" :data3 = "data.cond3" />
         </b-card>
      </b-collapse>
   </div>
</template>

Code:
        <script>
        export default {
          props: {
            component: String,
          },
    
          data() {
          },
    
          computed: {
            condition1() {
              const condition1 = true;
              if(condition1){
              return () => import(`../components/component1`);
              }
            },
              condition2() {
              const condition2 = false;
              if(condition2){
              return () => import(`../components/component2`);
              }
            },
              condition3() {
               const condition3 = true;
              if(condition3){
              return () => import(`../components/component3`);
              }
            },
          },
    
          created() {
           
            },
          },
        }
        </script>


I encountered an error when trying this implementation:

> Unknown custom element:<component> - did you register the component
> correctly? For recursive components, make sure to provide the "name"
> option.

It works fine with one condition, but throws an error when attempting multiple conditions and components.

Thank you for your assistance @power-cut.

Considering the expandable structure that requires displaying components separately, the single component approach is not suitable. 

Answer №1

When it comes to developing the Vue component, it's important to consider a different approach in this scenario. See below for an example of how you can create a dynamic component based on certain store conditions.

<template>
  <component :is="myDynamicComponent" />
</template>
<script>
import Component1 from './src/component1.vue'
import Component2 from './src/component2.vue'
import Component3 from './src/component3.vue'
export default {
  data() {
   return {}
  },

  computed: {
    myDynamicComponent() {
        switch (this.$store.state.foo) {
            case "condition1":
                return Component1;
            case "condition2":
                return Component2;
            case "condition3":
                return Component3;
            default:
                return Component1;
        }
     }
  }   
</script>

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

What is the best lifecycle hook to use for initializing components?

Below is an example where I am using the created lifecycle method to subscribe to the event service. Is this a common practice? Are there better or more appropriate ways or lifecycle methods to achieve the same functionality? const ViewComponent = { d ...

Returning to the location in the file where the redirect function was invoked in the Express framework

In my current project, I am working on an Express app and facing a challenge. I need to redirect after collecting data in a function, complete the redirect, return the data, and then resume from where I left off. For instance: > res.redirect('my/ ...

Interactive KML layer in ArcGIS mapping tool

Currently, I am working on enhancing an ArcGIS map by incorporating KML layers for interactivity. This is a simplified version of the code I am currently using: map = new Map("map", { basemap: "topo", center: [-108.663, 42.68], zoom: 6 }); parser.p ...

Using jQuery to animate a form submission in CodeIgniter

I have integrated two jQuery plugins into my application, which are: jQuery validate : . jQuery blockui : http://malsup.com/jquery/block/#download The application is developed using PHP Codeigniter and jQuery. It consists of a form created with the fol ...

Discover all related matching documents within a string array

I am using a mongoose schema model with a field called tags which is an array of strings to store tags for each document. I need functionality where if I search for a specific tag, such as "test," it will return all documents with tags like "testimonials" ...

Navigation Bar Dropdown Menu Not Responding to Clicks

I'm having trouble implementing a dropdown menu in my navigation bar that should appear when the user clicks and disappear when they click anywhere outside of it, similar to Facebook's dropdown menu with options like logout. However, for some rea ...

Could a user upload a video directly to their channel using an HTML/JavaScript form?

Would it be feasible to enable a user to upload a video to their channel via an HTML/JavaScript form? If this is indeed possible, I am unsure of how the Google authentication process would function on the user's end. The code examples provided pertain ...

Having trouble with PHP Storm and Vue component not working? Or encountering issues with unresolved function or method in your

I have been struggling with this issue for days and cannot seem to find a solution online. Being new to Vue.js, I am currently working on a TDD Laravel project: My goal is to add the standard Vue example-component to my app.blade.php as follows: app.bla ...

Updating every occurrence of a string in the visible text of a webpage: A step-by-step guide

I need to include the registered trademark symbol beside all mentions of a brand, which I'll refer to as "SomeBrand", on a client's website. Here is my current approach: function updateSomeBrand(){ var elements = document.getElementsByTagName( ...

When transmitting information to the server, the browser initiates four requests

I am encountering an issue with my React component. The problem arises when I try to retrieve the current geographic coordinates, as they are being fetched 4 times consecutively. This same glitch occurs when attempting to send the coordinates to the serv ...

Ways to dynamically toggle visibility and hide elements by clicking outside the specified div

I have a div that, when clicked, displays a contact us form. This form toggles between being visible and hidden. How can I make it hide when clicked on another part of the document? Here is the code: function showContactForm(){ var formWidth = &apos ...

Customize the background color of highlighted text using HTML and jQuery

Recently, I modified an existing code to divide plain text into four classes by selecting a portion of the text and coloring it. Afterwards, I extracted the text of each class and stored it in my database. While this code works well, I am looking for a way ...

JavaScript function to copy the first row of a table to the clipboard

I am new to JavaScript and I'm facing an issue with copying cells in a table. I have successfully created a table based on my MySQL database, but when I try to copy a cell using the copy button, only the first cell gets copied. I understand that I nee ...

Caution: It is essential for each child within a list to possess a distinct "key" property - React Native issue alert

Hello everyone, I am currently working on building a list in an app using react-native. I have been following a tutorial video and my code is identical to the instructor's, but I keep encountering an error that says each child in the list needs a key ...

Formik causing malfunction in MUI DatePicker functionality

In my React project, I am using Formik to manage form processing and MUI UI components for the user interface. While I can select the day and month, I'm experiencing an issue with the year part not updating. Even when I manually type in a year in the ...

How to use the var keyword in JavaScript to declare block-scoped variables

At this moment, my goal is to establish a block-scoped variable in JavaScript by utilizing the var keyword. I prefer not to utilize the let keyword due to compatibility issues with certain browsers in ecma6. Is there an optimal and universal method to ac ...

What are the steps to start a ExpressJS server for webpages that are not index.html?

I am exploring how to browse/run/view web pages other than just the index.html file in my public folder, which contains multiple HTML files. I am using ExpressJS and NodeJS for this purpose, but every time I start my server, I can only access the index.htm ...

Encountering a null value after making changes to the state in Reactjs

I'm currently working on a drag-and-drop web application using reactjs. The issue I'm encountering is that when I initiate the drag action, it triggers the handleDragStart function to update the state variable called selectedCard. However, when I ...

The powerful combination of ES6 and sequelize-cli

How can I execute sequelize migrations and seeds written in ES6? I attempted to use babel-node, but encountered a strange error. Command node_modules/babel-cli/lib/babel-node.js node_modules/sequelize-cli/bin/sequelize db:seed Error node_modules/b ...

What is the best method for integrating static files (such as css, images, js, etc.) into our Node.js application?

Here is the structure of my project folder: XYZ_PROJECT_FOLDER ASSETS CSS IMAGES JS VENDOR CONTACT.html INDEX.html INDEX.js In the INDEX.js file, I have included code to render all the static files and routing logic: const e ...