Managing different Vue dynamic components: mastering prop passing, event emitting, and slot replacement techniques

Just have some basic understanding of dynamic components, but what if the component is complex or unique from each other, how should I manage emit, props, and slots in the parent component?

Let's say I have 3 components:

Component 1

<template>
    <div class="app-container">
        <spinner :color="this.colore"></spinner>
        <slot></slot>
    </div>
</template>

This deals with loading, where I need to pass a prop "color" and some buttons in the slot.

Component 2

<template>
    <div class="app-container">
        <form>
            ......
            <button @click="onClick"></buttom>
        </form>
    </div>
</template>

method: {
    onClick: function () {
        this.$emit('form-submit');
    }
}

This component does not have any props or slots, but it emits an event when the button is clicked.

Component 3

<template>
    <div class="app-container">
        <header>
            <slot name="header"></slot>
        </header>
        <main>
            <slot></slot>
        </main>
        <footer>
            <slot name="footer"></slot>
        </footer>
    </div>
</template>

This component is simply for displaying information. However, it has 3 different slots.

Now, in the parent view, how can I correctly use dynamic components?

<template>
    <div class="homepage">
        <header></header>
        <keep-alive>
            <component :is="currentComp"/>
        </keep-alive>
    </div>
</template>

@Component({
    components: {
        Component1,
        Component2,
        Component3,
    },
})

export default class HomepageView extends Vue {

    public currentComp: VueConstructor = Component1;
    
    public switchToComp1: void {
        currentComp = Component1;
    }

    public switchToComp2: void {
        currentComp = Component2;
    }

    public switchToComp3: void {
        currentComp = Component3;
    }

}

I specifically need to pass props or replace slots for both comp1 and comp3. How can I properly implement the "switchToCompX" methods? And how do I handle the emit from comp2 since only comp2 will emit?

Answer №1

Objects can be used to pass both props and events, allowing you to store them in the data and switch content just like how you would switch an active component.

<button v-on="{ mousedown: doThis, mouseup: doThat }"></button>
<div v-bind="{ id: someProp, 'other-attr': otherProp }"></div>

Slots need to be defined in the template, so the best approach might be to define them all and then use v-if to activate only those required by the active component...

In simpler cases like this, using v-if instead of a dynamic component would be much more straightforward and efficient.

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

When an onClick event is triggered in jQuery, generate a certain number of div blocks based on the available list items, such as image source and heading text

Is it possible to generate input fields dynamically based on a dynamic list with checkboxes, labels, text, images, etc.? I currently have a working solution for checkboxes and labels using the code snippet below: let $checkboxContent = $('.checkboxes ...

Sending text from a Tinymce textarea using Laravel 4.2

I am currently facing an issue with a form that includes a tinymce textarea, allowing users to edit text and save it into a database with HTML tags for display on their profile. The problem arises when Laravel 4.2 escapes the HTML tags, making it difficult ...

Utilize multiple parameters in custom validation rules in Vue 3 with the help of vuelidate

I have a requirement for two fields named "price" and "max_price". Whenever I modify the "price" field, I need a validator to trigger the lessThanMaxPrice validation rule. Currently, everything is functioning as expected with this setup: <script setup ...

What is preventing me from using javascript setInterval with a function in a separate external file?

Everything is running smoothly with this code snippet...an alert pops up every 10 seconds <script type='text/javascript'> function letsTest(){ alert("it works"); } var uptimeId = window.setInterval(letsTest, 10000); < ...

Changing images upon hovering with preloading

I'm looking to enhance my logo listing with a hover effect that switches the logo from color to black and white. Here's the current markup I have: var sourceToggle = function () { v ...

Utilize restrictions (type/interface) on data types

When working with TypeScript, I am creating a type that consists of unions of other types: type A = B | C | D // ... One important requirement is that I want to ensure at compile time that B, C, D, and so on, have the structure of a generic template to en ...

Exploring the relationship between $resource and controllers

I am currently working on deciphering the code snippets below. From what I gather, there are three resource objects - CategorySrv, ArticleSrv, and SearchSrv that interact with REST server data sources. app.factory('CategoryService', function($re ...

How can a Vue component be created with a template that solely consists of a property's text?

Looking for a way to incorporate plain text within a Vue component template area? The current method involves wrapping the text in a div, but this causes layout issues when concatenating components with other text fragments. This results in awkward spacing ...

What could be the issue with the nodeValue property?

// html <div>Welcome Everyone!</div> // JavaScript var textElement = div.firstChild; textElement.nodeValue = "Hello Everyone"; Here is the example: example Why is it not possible to modify the text content? ...

I encountered an error in the Expo dashboard when attempting to upgrade from version 48 to 49 during the Expo Expo version change

For the image description, type in: "expo": "49", "react-native-reanimated": "~3.3.0", "expo-updates": "~0.18.19" I need assistance, can someone please help me out? ...

How to Access Qt QWebView Bridge in Webkit IFRAME for Local Page Content

After extensive effort, I successfully implemented the QtWebKit Bridge technique in my Qt C++ (Qt 5.5) application utilizing a QWebView widget. The local Webkit document can now call C++ functions thanks to this bridge. For more information on this techniq ...

What is the reason for the countdown number's color remaining the same even after it reaches a specific time threshold?

Creating a simple countdown for sports was my idea, but now I'm stuck on the "changeColor" part that I don't have enough knowledge about. The countdown is functioning perfectly, but customizing the colors and adding CSS animations seems challeng ...

Leveraging Modernizr in Angular testing suite

I have a Grails gsp that contains an Angular app. Within this setup, I have included the Modernizr library at the gsp level. Now, I am faced with the challenge of using this library in a directive unit test. Since Modernizr is used both inside and outside ...

Tips on displaying a message when search results are not found

import React, { useState, useEffect } from 'react' import axios from 'axios' function DataApi({ searchTerm }) { const [users, setUsers] = useState([]) const [loading, setLoading] = useState(false) const [error, setError] = useSta ...

Utilize the three.js library within a Vue component by importing it and incorporating its

Can someone please help me understand the proper way to import and utilize the three.js library in a vue component? Despite my extensive research, it seems that most individuals use the following code line to import three.js into a vue component. However, ...

Exporting Data in ReactJS

Hey there, take a look at the code snippet provided: import React, { Component } from 'react'; let ok; class Mydata extends Component { constructor() { super(); this.state = { rif: [{ "instituteName": ...

Updating the content within a div following the submission of a contact form 7

I'm struggling with my contact form. I want the content of my contact form div to change after clicking submit on the form. I've been searching for a solution, but so far, no luck. Here is what I have: Form (div1) with input fields, acceptance c ...

NodeJS Request Body Not Populated

Currently operating with node using [email protected] and [email protected]. Within my jade page, there exists a property like this: input(type='text',class='form-control', placeholder="Username", name='username', ...

Angular JS is encountering an issue where the promise object is failing to render correctly

I'm currently learning Angular and I have a question about fetching custom errors from a promise object in Angular JS. I can't seem to display the custom error message on my HTML page. What am I missing? Below is my HTML file - <!DOCTYPE htm ...

What is the best way to launch the default browser in a mobile webview?

As a front-end developer, I primarily work with javascript and vuejs. Recently, our team decided to incorporate webview into our native app project. This required me to create a mobile webview page for the app. The challenge I'm facing is that I have ...