简体   繁体   中英

calling parent function from cellrenderer like emit on vuejs ag-grid-vue

i have implemented the ag-grid-vue on my project now i have a seperate component on one of the columns which is basically Actions , now the user can either edit view or delete depending on the selection, now for edit and delete it works just fine, the problem is when i am deleting a record i want the table to be re-rendered by fetching the updated data from the Api, for that i need to call some method in the parent, from the CellRenderer Component, let me show you 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>

now the component above is where i need to make the changes, i tried to use the reqgular vuejs emit and on but that didnt work any help?

2 ways to solve this -

1. cellRendererParams approach

You can use cellRendererParams like this -

cellRendererParams : {
      action : this.doSomeAction.bind(this); // this is your parent component function
}

Now in your cell renderer component you can invoke this action

this.params.action(); // this should correspond to the object key in cellRendererParam

2. Using context gridOption

There is another way to solve this as described in this example

You basically setup context in your main grid component like this -

:context="context" (in template)

this.context = { componentParent: this };

Then in your component you can call parent component like this -

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

In my case @click event is being removed automatically. Am I missing something?

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

Actual Output:

<button >Click Me</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM