Developing effective communication between parent and child components in VueJS v-data-table.Let

Currently facing a challenge and seeking assistance: I have two Vuetify "v-data-tables" 1 - Parent table 2 - Children's table (which is actually a reusable component)

I am in search of a universal code snippet that I can tweak for my project, where every time I click on a row in the Parent table, the Child table will display corresponding details based on ID

I have browsed online for examples but haven't been able to customize them to fit my application. Here is an example link: enter link description here

<template>
   <div id="app">
       <table-component :data="fetchData">
           <table-column show="firstName" label="First name"></table-column>
       </table-component>
   </div>
</template>

<script>
    import axios from 'axios';

    export default {
        methods: {
            async fetchData({ page, filter, sort }) {
                const response = await axios.get('/my-endpoint', { page });

                // An object that has a `data` and an optional `pagination` property
                return response;
            }
        }
    }
</script>

Answer №1

I came across a solution to my issue and thought it would be beneficial to share it with you. Firstly, I utilized the "Event bus" approach which can be found in numerous tutorials and instructional videos. 1 - I created a JS file named bus.js with the following code:

import Vue from 'vue'
export const EventBus = new Vue()

2- Within the Parent component's Methods:

EventBus.$emit('id', id)

"Id" serves as the identifier for the selected ROW.

3- In the second Child component that contains the details:

EventBus.$on('id', id => {
      console.log(id)
      this.idSelect = id
      console.log('Mounted' + this.idSelect)
      this.loadContenu()
    })

loadContenu is the method responsible for fetching detailed data from the API. idSelect is a variable that receives the ID sent from the Parent component.

There you have it! I wanted to share this valuable experience with you all in hopes that it may prove helpful.

Answer №2

Here is an example demonstrating how to pass props between parent and child components:

Parent Component:

<template>
    <div>
        <div @click="passId('12345')">
        </div>
        <childComponent 
        :theId = theId
        />
    </div>
</template>
<script>
import childComponent from 'path/to/your/childComponent'
export default {

    components:{
        childComponent 
    },
    data(){
        return{
            theId:null
        }
    },
    methods:{
    passId(id){
        this.theId = id    
    }
    }  
}
</script>

Child Component:

<template>
    <div>
        <div v-if="theId">
            <!-- do something with theID here -->
        </div>
    </div> 
</template>
<script>
export default {

    props:{
        theId:{
            type: String,
            default:null
        }
    } 
}
</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

Generating an ordered array that begins at a specified value and has a specific number of elements

Searching for a stylish solution (without using a for loop) to generate a sequential array in Javascript that begins with a specific number and contains a set number of elements. For instance: Commencing with 2017 and including 4 items would appear as fol ...

Ensuring the vue carousel component stops rendering once all of its data has been displayed

Is it possible to stop rendering a vue carousel component once its data is displayed or after a certain amount of time? I've searched for information on this, but haven't found anything relevant. Despite it being an unusual request, I still want ...

using parameters to access django url via javascript

In my JavaScript function, I am passing parameters and using alert to confirm that the function is receiving the parameters correctly. However, when trying to pass these parameters in a Django URL, it is not working unless I pass a string instead. functio ...

Trigger a child component function in Angular by responding to user input

Within my application, there exists a parent component (pc) along with 4 child components (cc1, cc2, cc3, and cc4). Imagine a situation where a user inputs a number between 1-4 into a text field, and I want to call a specific function in the corresponding ...

problem encountered while installing npm global packages

I encountered a problem while attempting to install Vue CLI. Operating system: Windows 10, Node version: ~6.10.3 NPM version: ~3.10.10 npm WARN retry will retry, error on last attempt: Error: EBUSY: resource busy or locked, rename 'D:\Users&bso ...

Is there a way to inform TypeScript that a function within an object will fill in an empty property?

My issue resembles the following situation: Type Name = {firstName: string, lastName: string} class NameClass { public _name: Name | null; constructor() { this._name = null; } // any function here public set name(name: Name) { this._na ...

Secure your data with public key encryption and decryption using the Crypto Module in NodeJS

I have a challenge with encrypting/decrypting data using a public key that is stored in a file. The code snippet below illustrates my approach: encryptWithKey (toEncrypt, publicKeyPath) { var publicKey = fs.readFileSync(publicKeyPath, "utf8"); ...

sending parameters to a function provided by a different controller

I am facing an issue with passing parameters to a method declared in controller B, mentioned as conB.js and the code snippet looks like this module.exports.verify = function(req,res,next){ // how do I obtain the parameter here? } Now, I have conA.js. How ...

Is there a straightforward method for tallying numbers in mongoose?

Here's the code I've written: Company.count({}, function(err, company) { Checkpoint.count({}, function(err, checkpoint) { Guard.count({}, function(err, guard) { Device.count({}, function(er ...

Accessing information from a database and showcasing it within a tooltip

I have successfully implemented a tooltip feature using JavaScript and integrated it into an HTML page. Check out the code snippet below: $(document).ready(function () { //Tooltips $(".tip_trigger").hover(function (e) { tip = $(this).find('.tip&a ...

Problematic Situation Arising from JavaScript AJAX and NVD3.JS Unresolved Object Error

I am currently in the process of developing a script that will allow me to retrieve data for my chart from an external PHP file. Initially, I attempted manually inputting the data into the chart and it worked perfectly fine. However, when I tried using A ...

What is the best way to create a table of buttons with seamless integration, leaving no gaps between each button?

While developing a website, I encountered an issue where I couldn't figure out how to eliminate gaps between buttons. Despite searching online for a solution, I struggled to articulate my problem clearly. Essentially, I am trying to create a table lay ...

What is the proper way to generate relative paths in JavaScript within an MVC3 framework?

Struggling with aligning paths in JavaScript without hardcoding. Currently using an asp.net MVC3 web application. If the path looks like this: var url = 'http://serverNameHardcode/websiteNameHardcode/service/service?param1=' + param; Everythin ...

Include the jquery library and embed a Google Map

Hello, I am using jQuery load to refresh my page every second. The problem arises when I add a Google Map to the page - the map appears and disappears every second. Is there a way to fix this issue? $(document).ready(function(){ <?php if( ...

Utilizing cache for the onclick function on a multilingual website

I am currently working on developing a multi-language index page with a language change area. When I click on each language text, the language changes as expected. However, although the language changes when I click on my language links (AZ, EN, RU), it r ...

Determine the row index by identifying the row id and table id

I need to retrieve the Index number of a row when a hyperlink is clicked, while also passing additional data from this tag. <a href="javascript:void(0);" onclick="EditDoctorRow(' + RowCountDoctorVisit + ');"> <i class="fa fa-edit"&g ...

Exploring the concept of try-catch in JavaScript with a focus on the call stack within the Node

Recently, I delved into the world of Javascript and decided to explore how stack tracing functions in nodejs. Instead of looking at the source code, my lazy side led me to consult the language reference found at https://www.ecma-international.org/ecma-262/ ...

Tips on altering button color when input field is populated

I have been researching online and have not come across any discussions on how to dynamically change the color of a button in JavaScript when an input field is filled. I haven't really tried any code myself because there are very limited resources add ...

executing certain code in a JavaScript file for Internet Explorer 9 compared to all other web browsers

As I analyze this single line of code, my goal is to create a conditional statement that executes different actions based on whether the browser is Internet Explorer 9 or not. Here's the code snippet: ('.fa-phone, .bg-darkPink').parent().on ...

styled(MyComponent) will display MyComponent as is, without any extra styling applied

Two React components I have are utilizing styled-components. The first one named Div simply renders a basic div: import React from "react"; import styled from "styled-components"; export default function Div(props) { return <StyledDiv>{props.chil ...