invoking a parent function from a cellRenderer in Vue.js Ag-Grid through emit function

I integrated the ag-grid-vue into my project and added a separate component to one of the columns for user actions, such as Edit, View, or Delete. Editing and deleting records work fine, but when a record is deleted, I want the table to re-render by fetching updated data from the API. To achieve this, I need to call a method in the parent component from the CellRenderer Component. Here's an example of the code:

HTML

<ag-grid-vue
        ref="agGridTable"
        :components="components"
        :gridOptions="gridOptions"
        class="ag-theme-material w-100 my-4 ag-grid-table"
        :columnDefs="columnDefs"
        :defaultColDef="defaultColDef"
        :rowData="accounts"
        rowSelection="multiple"
        colResizeDefault="shift"
        :animateRows="true"
        :floatingFilter="true"
        :pagination="true"
        :paginationPageSize="paginationPageSize"
        :suppressPaginationPanel="true"
        :enableRtl="$vs.rtl">
      </ag-grid-vue>

JS

import CellRendererActions from "./CellRendererActions.vue"

  components: {
    AgGridVue,
    vSelect,
    CellRendererActions,
  },

columnDefs: [
{
          headerName: 'Account ID',
          field: '0',
          filter: true,
          width: 225,
          pinned: 'left'
        },{
          headerName: 'Account Name',
          field: '1',
          width: 250,
          filter: true,
        },
         {
          headerName: 'Upcoming Renewal Date',
          field: '2',
          filter: true,
          width: 250,
        },
        {
          headerName: 'Business Unit Name',
          field: '3',
          filter: true,
          width: 200,
        },
        {
          headerName: 'Account Producer',
          field: '4',
          filter: true,
          width: 200,
        },
        {
          headerName: 'Actions',
          field: 'transactions',
          width: 150,
          cellRendererFramework: 'CellRendererActions',
        },
      ],
components: {
        CellRendererActions,
      }

CellRenderer Component

<template>
    <div :style="{'direction': $vs.rtl ? 'rtl' : 'ltr'}">
      <feather-icon icon="Edit3Icon" svgClasses="h-5 w-5 mr-4 hover:text-primary cursor-pointer" @click="editRecord" />
      <feather-icon icon="EyeIcon" svgClasses="h-5 w-5  mr-4 hover:text-danger cursor-pointer" @click="viewRecord" />
      <feather-icon icon="Trash2Icon" svgClasses="h-5 w-5 hover:text-danger cursor-pointer" @click="confirmDeleteRecord" />
    </div>
</template>

<script>

import { Auth } from "aws-amplify";
import { API } from "aws-amplify";
    export default {
        name: 'CellRendererActions',
        methods: {
          async deleteAccount(accountId) {
            const apiName = "hidden";
            const path = "/hidden?id="+accountId;
            const myInit = {
              headers: {
                Authorization: `Bearer ${(await Auth.currentSession())
                  .getIdToken()
                  .getJwtToken()}`
              }
            };
            return await API.get(apiName, path, myInit);
          },
          viewRecord(){
            this.$router.push("/accounts/" + this.params.data[0]).catch(() => {})
          },
          editRecord() {
            // console.log(this.params.data);
            this.$router.push("hidden" + this.params.data[0]).catch(() => {})

            /*
              Below line will be for actual product
              Currently it's commented due to demo purpose - Above url is for demo purpose

              this.$router.push("hidden" + this.params.data.id).catch(() => {})
            */
          },
          confirmDeleteRecord() {
            this.$vs.dialog({
              type: 'confirm',
              color: 'danger',
              title: `Confirm Delete`,
              text: `You are about to delete "${this.params.data[1]}"`,
              accept: this.deleteRecord,
              acceptText: "Delete"
            })
          },
          deleteRecord() {
            /* Below two lines are just for demo purpose */
            this.$vs.loading({ color: this.colorLoading });
             this.deleteAccount(this.params.data[0]).then(() => {
                this.$vs.loading.close();
                this.showDeleteSuccess()
            });


            /* UnComment below lines for enabling true flow if deleting user */
            // this.$store.dispatch("userManagement/removeRecord", this.params.data.id)
            //   .then(()   => { this.showDeleteSuccess() })
            //   .catch(err => { console.error(err)       })
          },
          showDeleteSuccess() {
            this.$vs.notify({
              color: 'success',
              title: 'User Deleted',
              text: 'The selected user was successfully deleted'
            })
          }
        }
    }
</script>

In the above component, I tried using regular Vue.js emit and on, but it didn't work. Any suggestions on how to resolve this issue?

Answer №1

Here are two solutions for solving this issue:

1. Using cellRendererParams approach

To implement this solution, you can utilize the cellRendererParams property in the following manner -

cellRendererParams : {
      action : this.doSomeAction.bind(this); // This function belongs to the parent component
}

You can then invoke this action within your cell renderer component like so:

this.params.action(); // Ensure that key matches with object key in cellRendererParam

2. Leveraging context gridOption

An alternative method is explained in this example

In essence, you need to set up context in your main grid component as demonstrated below -

:context="context" (in template)

this.context = { componentParent: this };

Subsequently, within your component, you can access the parent component by invoking it like this -

invokeParentMethod() {
  this.params.context.componentParent.methodFromParent(
    `Row: ${this.params.node.rowIndex}, Col: ${this.params.colDef.headerName}`
  );
}

Answer №2

For some reason, the @click event seems to be disappearing on its own in my situation. Do you see what I might be doing wrong?

<button @click="editRecord" >Click Me</button>

Current Result:

<button >Click Me</button>

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

The jQuery library triggers an error that can only be resolved by refreshing the

I am currently experiencing an issue with my form (form links are provided below, specifically referring to form1). The problem arises when I include jquery.js, as it fails to load the doAjax and getIP functions that are contained in a separate js file nam ...

tips on incorporating chosen while still enabling text input

I am currently utilizing chosen to showcase a single selection from a lengthy array of choices. In addition, I am seeking the functionality to enable users to submit a choice that is not listed among the available options. This customization is specifica ...

I'm facing an issue where there is no "Access-Control-Allow-Origin" header present. Looking for assistance in converting it to JSONP using the POST method. Can anyone provide guidance?

Even though I have changed it to JSONP, the CORS error is still persisting. Here is the updated code snippet: $.ajax({ type: "POST", url: "<a href="https://api.api.ai/v1/" rel="nofollow noreferrer">https://api.api.ai/v1/</a& ...

Methods to display "typing" text while users are typing in Vue.js

Currently, I am developing a Vue project and I am looking for a way to display 'typing' or 'loading' text within the input placeholder as the user types. Can anyone assist me with this? ...

What is causing my React Query query function to be activated even though it is supposed to be disabled?

My goal is to dynamically set parameters and select a fetching function within a React Query function (useSpeciesCodes.js). The decision of which API endpoint to fetch from (using either getSpeciesCodesByRegion or getSpeciesCodesByAddress) should be based ...

What is the process of retrieving data from a Nextjs API route during the build and deployment stages?

I'm currently facing an issue while trying to deploy my nextjs web app on vercel. Upon deployment, I encounter the following error: > Build error occurred FetchError: request to http://localhost:3000/api/products failed, reason: connect ECONNREFUS ...

Revealing concealed content within a Bootstrap modal

I am seeking a way to utilize bootstrap modal in order to display certain contents. Specifically, the email, gender, and status information should initially be hidden and revealed only upon clicking the "view more" button. My goal is to showcase this dat ...

How can I dynamically adjust an element's attribute as a user scrolls past it (creating a sticky effect)?

For instance, when you visit and try scrolling up, you will notice a bar displaying: "Typography Code Tables Forms Buttons Icons by Glyphicons" As you continue to scroll past the element, a class is added to alter the appearance. However, as you scrol ...

Disabling the submit button after submitting the form results in the page failing to load

I am encountering an issue with my HTML form that submits to another page via POST. After the form validates, I attempt to disable or hide the submit button to prevent double submission and inform the user that the next page may take some time to load. He ...

Am I causing my entire React component to re-render needlessly every time the state changes?

I've been attempting to develop an accordion component using React, but I seem to be encountering issues with the animation not functioning as expected. The approach I'm taking is quite standard - setting a max-height of 0 for each item body and ...

Looking for guidance on configuring an email composer in a PhoneGap application

Seeking assistance in troubleshooting the email composer plugin for my PhoneGap app (using JQueryMobile). In my config.xml, I have included the plugin as shown below; <plugin name="cordova-plugin-email-composer" spec="https://github.com/katzer/cordova ...

Syntax error: Your code encountered an unexpected closing curly brace

Here is the code snippet I am working with: <?php session_start();?> <!DOCTYPE html> <html> <head> <title>Narcis Bet</title> <meta charset="utf-8"> <link rel="stylesheet" href="css/style.css" type="text/css"&g ...

The error TS2339 is indicating that there is no property called myProperty on the type SetStateAction<User>

I'm encountering a TypeScript error while working with React that's leaving me puzzled: <html>TS2339: Property 'subEnd' does not exist on type 'SetStateAction&lt;User&gt;'.<br/>Property 'subEnd' d ...

Execute a database query to search for patterns using Regular Expressions within the

As I embark on a new project, I find myself questioning my approach before diving in too deep and realizing it may not be the most efficient path. Within the realm of a large company where we develop unofficial tools for internal use, I am faced with limi ...

ReactJS Error: Cannot find reference to 'require'

I'm currently implementing the DRY concept in React JS by attempting to reuse the same HTML partial across different files. Here is the partial: var AdminMenu = React.createClass({ getInitialState: function() { return {}; }, render: function() ...

2 mistakes: (Uncaught ReferenceError: require isn't defined) & (npm ERR! script missing: start)

Issue #1: Environment Variables I am facing a problem with my JavaScript files app.js (main) and request.js. Both files are at the same level in the root directory, just like index.html. The request.js file contains process.env.APP_KEY. I attempted to i ...

Encountering a 500 server error while trying to send an email using SendGrid in conjunction

Seeking help on integrating an email capture form into a NextJS site by following this tutorial: Simplified the form to only include the email field. The content of my api/contact.js file is as follows: const mail = require('@sendgrid/mail'); ...

Executing a separate function after each iteration of an ajax call within a loop using Jquery

I am faced with a situation where an ajax function must be run inside a loop that depends on the array's size. How can I execute another function after the ajax call is completed and outside the loop? Is this achievable? Below is the function: funct ...

Using JSON Filtering with React

I am currently working on fetching JSON data and implementing a filtering feature for the displayed content. An error that I am encountering is: Uncaught TypeError: Cannot read property 'toLowerCase' of undefined Any insights on what might be ...

Show a compact graphic in the upper-right-hand corner

Hey, I have this interesting idea but CSS isn't my strong suit. Any thoughts on how to achieve it? I'm looking to create a new class that, when applied to an item (like a div), displays a small clickable pre-defined image in the Top-Right corne ...