How to Activate Child Component in Vue When Submitting a Form

This is my PhoneLineNumberComponent. Everything is working perfectly, but I'd like to have the child component form loaded when the user clicks the button on the parent component. The PhoneLineNumberComponent is the child component, and the ButtonComponent is the parent component.

<template>
    <div>
        <form v-for="(line,index) in lines" v-bind:key="index">
            <div class="form-group">
                <div class="col-lg-6">
                    <div class="row">
                       <div class="form-group">
                       <input v-model="line.number"
                                   float-label="Phone Number"
                                   numeric-keyboard-toggle
                                   placeholder="5551234567"
                                   type="text"
                                   class="form-control"
                                   value="" />

                        </div>
                    </div>
                </div>

                <button type="button" v-if="index + 1 === lines.length"  @click="addLine">Add</button>
                <button type="button" @click="removeLine(index)">Delete</button>


            </div>
            </form>
    </div>
</template>

<script>
    export default {
        name: 'PhoneNumberLineComponent',
        data() {
            return {
                lines:[],
                blockRemoval: true,
                index:[],
            }
        },
        watch: {
            lines() {
                this.blockRemoval = this.lines.length <= 1
            }
        },
        methods: {
            addLine() {
                let checkEmptyLines = this.lines.filter(line => line.number === null)
                if (checkEmptyLines.length >= 1 && this.lines.length > 0) return
                this.lines.push({
                    countryCode: null,
                    number: null,

                })
            },
            removeLine(lineId) {
                if (!this.blockRemoval) this.lines.splice(lineId, 1)
            }
        },
        mounted() {
            this.addLine()
        }

    }
</script>

<style scoped>
</style>

This is my ButtonComponent. When the user clicks the button on the ButtonComponent, the PhoneLineNumber child component should be triggered.

<template>
    <div>

        <PhoneNumberLineComponent></PhoneNumberLineComponent>

    </div>
</template>

<script>
    import PhoneNumberLineComponent from './PhoneNumberLineComponent';
    export default {
        name:'ButtonComponent',
        components: {
            PhoneNumberLineComponent
        },
        data() {
            return {
                lines: [],
                blockRemoval: true,
                index:[],
            }
        },

    };
</script>

<style scoped>
</style>

Answer №1

To assign control-clicked data to a boolean variable like toggleShow and use v-if to trigger your component, follow the code snippet below:

<template>


    <div>

        <PhoneNumberLineComponent v-if="toggleShow"></PhoneNumberLineComponent>

        <button @click="toggleShow = !toggleShow">Button</button>
    </div>


</template>

<script>
    import PhoneNumberLineComponent from './PhoneNumberLineComponent';
    export default {
        name:'ButtonComponent',
        components: {
            PhoneNumberLineComponent
        },
        data() {
            return {
                lines: [],
                blockRemoval: true,
                index:[],
                toggleShow: false
            }
        },

    };
</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

Tips for populating category and subcategory using JSON data

When creating an admin form in React, I want to have a Category and sub-category dropdown selection with options populated from a JSON file (categories.json). The respective sub-categories should be displayed based on the selected category while adding a n ...

Verify if the element in the array is set to true

Using a simple boolean in a condition is straightforward : var running = true; if(running) {/*do something*/} But what about using a boolean array? Can it be done like this: var running = [false,false,true,false]; if(running[]){/*do something*/} Curren ...

What is the best way to connect v-model with a select element when dealing with nested foreach loops?

Whenever I use alert(this.property_credentials.district) in vue.js, it returns empty <select v-model="property_credentials.district" name="district" class="country selectpicker" id="selectCountry" data-size="10" data-show-subtext="true" data-live-searc ...

Is it necessary to have NodeJs in order to host a React app on a server?

I've been working on a .NET Core 2.2 project with React integration, As I'm nearing completion of the project, I have a query that has been on my mind. Do I need Node.js installed on the server for React to function properly? Thank you. ...

Encountering an Issue with Missing Registration Error When Making HTTPPost Requests to GCM in Google Apps Script

I am attempting to send an HTTP POST request to the GCM server using Google Apps Script. I have both the device ID and the necessary credentials. Below is the code I am currently using: function doThat(){ var url = "https://android.googleapis.com/gcm/se ...

What is the best way to partition JSON data from an API request in React and display it in various sections within the component

There are 2 JSON objects that contain sales period details based on Month to date and year to date. The data includes information such as Units Sold, Gross Revenue, Year to Date Totals, Month to Date Averages, Expenses, Net Revenues, and Per Unit values. I ...

Guide on transforming OBJ/FBX files into GLTF format prior to adding them to your scene with Threejs

Currently, I am working on developing a web application that allows users to upload obj/fbx files and view them directly in the browser. The utilization of OBJLoader and FBXLoader provided by Threejs has been successful so far. However, I have a specific r ...

Delete the file containing Mongoose references

I'm facing an issue with deleting questions when a survey is deleted in the Survey model. Even after deleting the survey, the question remains intact in the database. Survey Schema: let surveyModel = mongoose.Schema( { Title: String, T ...

Is there a way for me to dynamically incorporate new elements into this object?

I am working with an object msg.data that contains the following information: { "user_id": 1, "success": "true" } Now, I want to add a name field to this list: { "user_id": 1, "success": "true", "name" : "giri" } I have attempted the following ...

How about starting a Node.js application with specific configurations?

Is there a way to develop a Node.js app that can be initiated with additional parameters? Here are a few examples: node myApp.js -nolog This command would initialize the app with the custom parameter noLog=true, preventing console logging. node myApp.js ...

How can you incorporate a value into a variable in PHP?

Hey there! I'm pretty new to PHP and I've been working on building a program that resembles a spreadsheet. My form consists of columns and cells, allowing users to add or delete rows using Javascript. The challenge I'm facing is automating t ...

Angular2 does not load Js twice

I specified the path to my JS file in angular.cli. It loaded successfully during the initialization of the Angular app, but when navigating back to the component, it failed to load. Any suggestions on how to fix this issue would be greatly appreciated. Th ...

How to reach the Twitter share iframe with JavaScript/HTML

There seems to be an issue with the Twitter share button not displaying at its full width on certain pages. Upon investigation, I discovered that the iframe containing it is only set to a width of 24px, when it should actually be set to the correct width. ...

Developing an edit form using Vue and Axios: Incorporating a dynamic database value into the form field

I am currently working on an edit form using Vue and Axios, but I have encountered a conflict. Here is my Vue code: <script> import { required, minLength } from 'vuelidate/lib/validators' export default { created() { this ...

The Angular error TS2531 occurs when attempting to call scrollIntoView on an object that may be null

In my current Angular project, I am attempting to implement a scroll view using ViewChild by id. This is the method I have written: ngOnInit() { setTimeout(() => { if (this.router.url.includes('contact')) { ...

Trouble encountered while attempting to utilize @click="checkedInput" for displaying checkbox label in Vue.js?

const app = new Vue({ el: '#app', data: { checkedNames: [], checkedName: true, close: false }, methods: { uncheck(checkedName) { this.checkedNames = this.checkedNames.filter(name => name !== checkedName); }, ...

HTML: Base64 image not displaying properly due to incorrect height specification

I have a straightforward base64 image that I am having trouble with. The issue is that only the upper half of the image is displaying. If I try to adjust the height using the "style" attribute in the img tag: style="height: 300px;" it shows correctly. Ho ...

Calculating the total of table elements with vuejs

I'm currently working with Vue.js and I need to calculate the total amount in a table that includes quantity, unit price, and their totals. I want to achieve this by looping through the database elements and using v-if to filter out certain elements. ...

Javascript - Execute function after all nested forEach loops have finished running

I'm finding this task to be quite challenging, as I am struggling to comprehend it fully at the moment. The issue involves nested forEach loops, and I require a callback function to execute once all the loops have finished running. I am considering u ...

What is the best way to style radio boxes in HTML to resemble checkboxes and display X's when selected?

I'm looking to create a form with radio boxes that resemble checkboxes and display a glyphicon x when selected. I've experimented with various solutions such as: input[type="radio"] { -webkit-appearance: checkbox; /* Chrome, ...