Load a new Vue component within a parent Vue component based on the user's selection from a dropdown menu

Within my Vue.js application, I have implemented a component called

commonform.vue

This form includes a dropdown menu for users to select a schedule type.

Depending on the selected schedule type, the remaining form fields should adjust accordingly.

While there are three common fields for all types:

user name, schedule name, and schedule type
, these fields remain consistent within commonform.vue. However, the other fields will dynamically change based on the user's selection...

To streamline this process and avoid excessive if-else logic in commonform.vue,

I have created distinct Vue components for each scenario such as:

typeonefields.vue and typetwofields.vue... etc

My query is,

How can I load these components dynamically inside fullform.vue depending on the chosen schedule type?

The schedule type selection code snippet is shown below:

<cs-dashboard-select
                                        :options="[
                                            { value: '1', label: 'Type common'},
                                            { value: '2', label: 'Type one'},
                                            { value: '3', label: 'Type two'},
                                            { value: '4', label: 'Type three'},
                                        ]"
                                        name="schedule_type"
                                    > Select type
                                    </cs-dashboard-select>

If the user opts for Type one, then the form fields should include:

user name, schedule name, schedule type, type one field

Similarly, for Type two, it should display:

user name, schedule name, schedule type, type two field

Answer №1

You can easily accomplish this by triggering an event from commonform.vue (when a scheduled type is selected) to fullform.vue and then using v-if to dynamically display the necessary component in the DOM.

Below is how the logic is implemented:

Main component (fullform.vue) :

<div>
    <commonform v-on:selected-option="getSelected($event)"></commonform>
    <typeonefields v-if="showComponent === '2'"></typeonefields>
    <typetwofields v-if="showComponent === '3'"></typetwofields>
</div>

methods: {
    getSelected(event) {
      this.showComponent = event;
    }
}

Child component (commonform.vue) :

<cs-dashboard-select
     :options="[
         { value: '1', label: 'Type common'},
         { value: '2', label: 'Type one'},
         { value: '3', label: 'Type two'},
         { value: '4', label: 'Type three'},
     ]"
     name="schedule_type"
     v-model="selectedValue"
     @change="onChange"
> Select type
</cs-dashboard-select>

methods: {
    onChange() {
        this.$emit("selected-option", this.selectedValue);
    }
}

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 way to extract a value from a string containing a list of maps?

I am currently facing a requirement where I need to extract values from a map in the following format: "{xyz=True, abc=asd-1123, uvw=null}" The challenge is to retrieve these values from a string representation of the map. I have attempted usi ...

Improving react-google-markers with a new search filtering system

In my controlled component, I have a list of markers and an input field for searching within that list. Concurrently, there is a map component adjacent to the marker list component. While the search functionality updates the marker list appropriately, the ...

Error message appears: "Unable to access 'upgrade' property of undefined" upon launching Vue application

Everything was running smoothly with my project for a few months. I could easily execute npm run serve without any issues, even when switching networks. But now, no matter what I do, I can't seem to get the server to start again. The error message I&a ...

I am looking to download a file from a server and showcase it in a browser using React.js. The file will be received as a response from the

**I am looking to retrieve a file from the server by sending the file name through the body and then receiving the requested file from the server.** I have successfully received the file in response from the server, which I tested using Postman. What I a ...

Send various arrays from a PHP file to JavaScript

Currently, I am extracting a large amount of data from a PHP file organized into multiple arrays. My goal is to transfer all this data to my JS file and then display each array in different sections of the website. To achieve this, I plan to consolidate al ...

"Calling getElementByID results in a null value being returned (see example in the provided

In my attempt to design unique buttons for a media player, I encountered a challenge. I envisioned the play button transitioning into a "loading" button and eventually into a pause button. My solution involved using 4 div elements - stop, play, loading, a ...

Guide to importing csv documents into a Nuxt Vue component

I have been working on loading a csv file into a Nuxt page. The folder structure is as follows and I keep encountering the error message "Failed to load resource: the server responded with a status of 404 (Not Found)": Project | +--pages | ...

"Using Mongo and Express to retrieve a user by their ID results in an object being null

I've been attempting to retrieve a user object by ID using User.findById. When I make the request in Postman, it returns "user": null, even though the object with the included ID contains fields. Example of my object: { "_id" : ObjectId("5b3ca ...

Getting the name of a component in Vue using webpack vue-loader

Recently, I have been immersing myself in the Vue documentation and learning about components. However, there is one thing that is confusing me. The documentation mentions different ways to register a component: Global Registration Vue.component(' ...

How can you make nested JSON values optional in Joi Validation?

As I work on my API, I encounter a nested JSON structure that serves as the payload for the endpoint. Here is an example of what it looks like: {"item_id":"1245", "item_name":"asdffd", "item_Code":"1244", "attributes":[{"id":"it1","value":"1"},{"id":"it2" ...

Menu changes when hovering

I want to create an effect where hovering over the .hoverarea class will toggle the visibility of .sociallink1, .sociallink2, and so on, with a drover effect. However, my code isn't working as expected. Additionally, an extra margin is automatically ...

Node.js Global Variables and Functions Explained

If I have a JavaScript file like the one below, containing global variables and functions, what is the best way to include it in Node.js with Express? var language = { 'English': 'English' } var a = 'string'; function s ...

Steps for dynamically adjusting form fields depending on radio button selection

I am looking to create a dynamic form that changes based on the selection of radio buttons. The form includes textfields Field A, Field B, ..., Field G, along with radio buttons Radio 1 and Radio 2. I need to update the form dynamically depending on which ...

"Looking to access your Express app in a VM from the internet? Here's how

I have an express app running on a Node.js server hosted on Azure Linux VM, and I am looking to access this website from my personal computer. const express = require('express'); const app = express(); app.listen(3000, () => { console.lo ...

Determine the outcome of the assessment quiz

Greetings everyone, I apologize for my poor English. I've been searching through numerous documents, but due to my language barrier, I am having trouble understanding them. I have designed a quiz page, but I'm facing an issue where I can't d ...

The Angular HTTP POST request is not transmitting any data - there is no body visible even in the Chrome debugger

I'm completely baffled by this situation. It's a routine task for me, yet I can't figure out why it's failing in such a strange way. It seems like it's going to be something trivial, but it's not the typical "no data on the se ...

Each time guildMemberAdd is triggered in Discord.js, it may not run consistently

At times, I am left baffled by the inconsistency in behavior of this code. Sometimes it works like a charm, while other times it refuses to add people for hours on end, only to randomly start working again. Any suggestions on how I can resolve this issue? ...

What is the best way to send $(this) to a function?

Here is my code snippet: $(document).ready(function(){ var hCount = 0, eCount = 0, nCount = 0, mCount = 0; $("#head").click(function() { var pPos = calculatePosition(hCount); $(this).animate({left:pPos+"px"}, ...

How can I automatically direct my NodeJS application to the login screen?

Here is the setup of my project structure: There is a simple folder called static, within which I have: index.html (the homepage for user registration) login.html (the login page) In the parent folder, there is a file named server.js: // NodeJS code for ...

Detecting when the user exits AR mode in A-Frame

In my A-Frame project under development, users are given the option to choose between playing the game in AR mode or traditional non-AR 3D mode. If a user unexpectedly leaves AR mode (by exiting fullscreen, for example), it is crucial for us to detect thi ...