What is the most effective way to ensure that a child component only executes when a link is clicked on the Vue component?

There are two components in my code

The first component, which is the parent component, looks like this :

<template>
    <ul class="list-group">
        <li v-for="item in invoices" class="list-group-item">
            <div class="row">
                ...
                <div class="col-md-7">
                    ...
                    <a href="javascript:"
                       class="toggle-show"
                       aria-expanded="false"
                       data-toggle="collapse"
                       :data-target="'#' + item.id"
                       @click="show(item.id)">
                        Show <span class="caret"></span>
                    </a>
                </div>
            </div>
            <div class="collapse" :id="item.id">
                <order-collapse/>
            </div>
        </li>
    </ul>
</template>
<script>
    import orderCollapse from './orderCollapse.vue'
    export default {
        ...
        components: {orderCollapse},
        data() {
            return {
                invoices: [
                    {
                        id: 1,
                        ...
                    },
                    {
                        id: 2,
                        ...
                    },
                    {
                        id: 3,
                        ...
                    }
                ]
            }
        },
        methods: {
            show(id) {
                // The orderCollapse component will be executed if this method is run
            }
        },
    }
</script>

The second component, which is the child component, looks like this :

<template>
    <table class="table table-bordered table-collapse">
        <!-- This is used to display details by id -->
    </table>
</template>
<script>
    export default {
        name: 'order-collapse',
        ...
    }
</script>

If the parent component is executed, the child component will automatically be executed as well

I want to prevent the child component from being executed when the parent component is executed

I want the child component to be executed only when a user clicks on the "Show" link

How can I achieve this?

Answer №1

If you want to manage the display status of each order-collapse element, consider creating a property called "displayedIds" and use the v-if directive to conditionally show them:

<div ... v-if="displayedIds[item.id]">
    <order-collapse :id="item.id"></order-collapse>
</div>

Initially declare displayedIds as an empty object {} and define the show() method like this:

  methods: {
    show(id) {
        // Use $set to make it reactive
        this.$set(this.displayedIds, id, true);
    }
  },

To simplify, you can also use an array for displayedIds and push the id into it using just .push(). Then check if the item.id is included in the displayedIds array:

<div ... v-if="displayedIds.includes(item.id)">
    <order-collapse :id="item.id"></order-collapse>
</div>

Another option is to add a "displayed" property to each item itself and toggle its value on click:

<a ... @click="show(item)">

<div ... v-if="item.displayed">
    <order-collapse :id="item.id"></order-collapse>
</div>

The recommended approach depends on your preference. Adding a "displayed" property to each item is simpler, but using an object or array for displayedIds may be more versatile depending on your needs.

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

Steps to customize Button Color and Label in a specific cell within a Material UI Table

I've implemented the Material Table to display my data, and it seems like this: In my code, I have a declared state as follows: const [sharedOrdersList, setShareOrdersList] = useState([]) When the User clicks the Share button, I push the Order Id in ...

several different objects within the rightIconButton of a ListItem component in MaterialUI

I am currently working on a project where I need to add multiple elements to the rightIconButton of a ListItem. The tools I am using are Material UI v0.20 and [email protected] <ListItem rightIconButton={ <span> ...

bxSlider adds in an empty slide after deleting an image

Whenever I click a link in my navigation, I want to remove certain images from the page. I tried implementing a solution, but now I have two empty spaces where the images used to be. How can I remove those as well? I searched on Stack Overflow for a soluti ...

The dropdown in MaterializeCSS does not display any data retrieved from VUE

Good evening. I am currently utilizing VUE along with MaterializeCSS. I have been trying to populate a selection menu without success. Although I am receiving the data from the database correctly, the options in the select tag remain blank when using V-F ...

React's connect method is causing issues with my test case

Attempting to create a test case for my jsx file... Took a sample test case from another jsx file... The other file does not have the connect method... But this new file contains the connect method... Believe this is causing issues with my test case... Any ...

Retrieving attribute values when using the .on function in jQuery

I currently have 10 links with the following format: <a href="#" data-test="test" class="testclass"></a> as well as a function that looks like this: $(document).on("click", ".testclass", function () { alert($(this).attr('data-t ...

Is it considered poor form to send as many as 100 ajax requests when loading a webpage?

My table can display up to 100 rows, sometimes even more. Is it considered a bad practice to loop through all these rows and send an AJAX post request to fetch data? I am hesitant to do this during the page load as it may significantly slow down the loadin ...

Working with Vue.js: accessing nested data from child components within a v-for loop

When working with a v-for loop, my goal is to group every 4 results retrieved from the API into a single row. <div v-for="(item, index) in this.info.length/4" :key="item"> <el-col v-for="thing in this.info" :key="thing"> {{ thing }} ...

The Electron forge project from publisher-github is failing to detect the environment variable GITHUB-TOKEN

I've set up my .env file with the correct token, but I encountered an error when trying to publish my package on GitHub. An unhandled rejection has occurred inside Forge: Error: Please set GITHUB_TOKEN in your environment to access these features at n ...

Unlock exclusive design features from beyond a Component's borders (NativeScript + Vue)

My application is made up of: 6 different components within the component folder, 3 JavaScript files located in the library folder. Within component_1, there is a Layout with a reference called myLayout. One of the JS files, myLayoutHandler, manipulates ...

Why does Vue 3 template display 101 instead of 1 when incrementing the number from 0?

Vue.createApp({ data() { return { counter: 0 } }, template: '<div>{{counter++}}</div>' }).mount('#root') Ultimately, the code above displays the number 101 on the page. Any insights into why this is happ ...

Does ECMAScript differentiate between uppercase and lowercase letters?

It has come to my attention that JavaScript (the programming language that adheres to the specification) is sensitive to case. For instance, variable names: let myVar = 1 let MyVar = 2 // distinct :) I have not found any evidence in the official specific ...

Ways to emphasize the contrast between two texts using CSS

One method to highlight specific parts of text using CSS can be found in this script: span.highlight { background-color: #B4D5FF; } However, what if we want to highlight the differences between two strings? Take for example these two strings: this ...

Reveal the MongoDB database connection to different sections within a Next.js 6 application

Currently developing an application using Next.js v6, and aiming to populate pages with information from a local mongodb database. My goal is to achieve something similar to the example provided in the tutorial, but with a twist - instead of utilizing an ...

Issue with jQuery.off when using a dynamic function name

I am currently implementing a modular pattern for writing my JavaScript code and it has been an enjoyable experience! However, I have encountered a challenging situation. My Namespace structure looks like this: var settings, handlers, objects, Namespace ...

Initiate a click on a radio button while also retaining the selected option when the page is

This is a unique question. In my scenario, there are two radio buttons: "radio1" and "radio2." I have successfully implemented the following actions individually: Automatically triggering a click on "radio1" upon page load. This ensures that the button ...

Using "array_agg" in a "having clause" with Sequelize

I am facing a particular scenario with my database setup. I have three tables named computers, flags, and computerFlags that establish relationships between them. The structure of the computerFlags table is as follows: computerName | flagId computer1 | ...

Ways to activate the enter key

Here we have the input bar and search button setup in our HTML code: <div> <div class="input-group search-bar"> <input type="text" class="form-control search-box" placeholder="Search people" autofocus="" ng-model="searchPeople"& ...

javascript making a button using an object

When trying to create a button from a JavaScript object, I am following this approach: for (buttonName in buttons){ var htmlbutton = '<button type="button" onclick="'+buttons[buttonName]()+'">'+buttonName+'< ...

AlphaVantage Platform: Element not found

As someone new to API services, I'm currently working on constructing a dashboard that pulls data from the Alphavantage API. My goal is to retrieve data for 3 symbols simultaneously by creating a list and passing the index to my API call. Each symbol ...