Passing an array list back to the parent component in ag-grid(Vue) - A step-by-step guide

Currently, I am integrating AG Grid with Vue. My project has a specific requirement where two checkboxes are displayed using a cellRendererFramework. However, I am facing difficulties in fetching the values of these checkboxes from the row definitions. The goal is to be able to select rows based on which checkboxes are checked within the ag-grid.

Below is the code for the child component:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.11/vue.js"></script>
<template>
<input type="checkbox" :id="inputId" :name=name @click ="clickHandler($event)" />
</template>
<script>
  import Vue from 'vue';
  export default Vue.extend({
    name: 'CheckBoxRenderer',

    data: function() {
      return {
        id: '',
        name: '',
        inputId: '',
        rx1List: [],
        rx2List: [],
      };
    },
    beforeMount() {
      this.id = this.params.data.id;
      this.name = 'rx' + this.id;
      this.inputId = this.params.column.colId + '_' + this.id; // if colId(headerName) ="rx1", and id is 2, inputId = rx1_2
    },
    methods: {
      clickHandler(e) {
        //console.log(e.target.checked, this.params.column.colId); //  to get Header name use colId property
        var group = document.querySelectorAll(`input[name="${this.name}"]`);
        // console.log(group.length);

        if (e.target.checked) {
          for (var i = 0; i < group.length; i++) {
            //console.log(group[i].checked);
            group[i].checked = false;
          }

          e.target.checked = true;
          if (this.params.column.colId === 'rx1') {
            this.rx1List.push(this.id);
          }
          console.log(this.rx1List);
        } else {
          e.target.checked = false;
        }

      }
    }
  });
</script>
<style scoped></style>

Here is the parent component's ag grid column definition:

 {
                field: "rx1",
                headerName: "Rx1",
                cellRendererFramework: "checkBoxRenderer",
                valueSetter: function (param) {
                    var id = "rx1_" + param.data.id;
                    alert("if check box checked?: ", document.querySelector(id).checked);
                    param.data.rx2 = document.querySelector(id).checked;
                    console.log("Rx2: ", param.data.rx2);
                    return param.data.rx2;
                },
                flex: 1,
                maxWidth: 80,
                cellStyle: { textAlign: "center"},
                
            },

Answer №1

To streamline the process, define the click handler in the parent component and then pass it down to the child as a prop. By doing this, the child component will only need to call the prop while the parent component keeps track of the checked state(s) and renders the grid accordingly. Below is a simple and contrived example:

Vue.config.productionTip = false;

const Child = {
  name: 'Child',
  props: ['onCheck'],
  methods: {
    handleCheck(e) {
      console.log(`${e.target.checked ? 'Checked' : 'Unchecked'}, let's call our onCheck prop`);
      this.onCheck(e);
    }
  },
  template: `<div><input type="checkbox" id="checkbox1" @change="handleCheck($event)" /></div>`,
}

const Parent = {
  name: 'Parent',
  data() {
    return {
      state: false,
    };
  },
  methods: {
    handleCheck(e) {
      console.log("Got a click event from child!");
      this.state = e.target.checked;
    }
  },
  components: { Child },
  props: [],
  template: '<div><Child :onCheck="handleCheck" /><div>state: {{ state }}</div></div>',
};

const App = new Vue({
  el: '#root',
  components: { Parent },
  template: '<Parent />',
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="root"></div>

On a side note, consider using @change instead of @click for checkboxes.

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

What is causing the 'transitionend' event to trigger multiple times?

Currently, I'm honing my JavaScript skills by taking on the 30 days of JavaScript challenge. I'm puzzled by why the 'transitioned' event is triggered twice in the code snippet below. My CSS only contains one property called transform, ...

Tips for directing attention to a specific row with an input field in JavaScript

I duplicated a table and added an input field for users to search or focus on a specific row. However, there are two issues: When a user enters a row number, the table displays the wrong row - for example, if the user enters 15, the table shows row number ...

Adjust the color of the entire modal

I'm working with a react native modal and encountering an issue where the backgroundColor I apply is only showing at the top of the modal. How can I ensure that the color fills the entire modal view? Any suggestions on how to fix this problem and mak ...

Replicating form fields using jQuery

I have come across many questions similar to mine, but unfortunately none of them address the specific details I am looking for. On a single page, I have multiple forms all structured in the same way: <form> <div class="form-group"> ...

Struggling to make Tumblr Javascript function properly

I have integrated the following code snippet: <script type="text/javascript" src="http://underlineent.tumblr.com/api/read/json"> </script> Unfortunately, my Tumblr blog is not appearing on this site. Can anyone provide assistance? The provid ...

Listening for time events with JQuery and controlling start/stop operations

I recently developed a jQuery plugin. var timer = $.timer(function() { refreshDashboard(); }); timer.set({ time : 10000, autostart : true }); The plugin triggers the refreshDashboard(); function every 10 seconds. Now, I need to halt the timer for ...

Stop geocomplete from providing a street address based on latitude and longitude coordinates

Is there a way to prevent geocomplete from displaying the street portion of the address when passing lat and lng coordinates? Here's an example: If I pass these coordinates to geocomplete: var lat = '40.7127744' var lng = '-74.006059& ...

How to conditionally disable the @click event on an image element in Vue.js

I am presenting the code snippet below: <image id="wheel-bg" class="wheel-bg" :x="-width/2" :y="-height/2" href="images/wheel-bg.png" :width="width" :height="he ...

Is there a way to incorporate jQuery into SharePoint 2010?

I am encountering an issue with linking my HTML page to our organization's SharePoint 2010 portal. All necessary files (CSS, images, jQuery) are stored in the same document library. While the CSS is functioning properly, I am facing challenges with ge ...

Steps for incorporating the getElementByClassName() method

I have developed an application that features a list displayed as shown below: https://i.stack.imgur.com/BxWF2.png Upon clicking each tick mark, the corresponding Book name is added to a textbox below. I desire the tick mark to be replaced by a cross sym ...

Maximizing the potential of Angular forms through native FormData

Currently, I am revisiting an older project that still uses traditional methods for form submission. The HTML includes a form element with defined method and action. My goal is to submit the form in the old-fashioned way using the action attribute to post ...

Having trouble with creating a new Next.js app using the latest version with npx?

Having some difficulty with the "npx create-next-app@latest" command while setting up Next.js. As a newcomer to both the community and Next.js, I could use some assistance in resolving this problem. Upon running the command, an unfamiliar message was displ ...

What is the best way to align these div elements within a table cell?

I am encountering an issue with the placement of elements. What I am striving for is something like this: https://i.stack.imgur.com/VSFXE.png where a div with several other divs inside is positioned at the top of the td, and another div is at the bottom o ...

Using Jquery to swap out div elements and reinitialize code after selecting a menu <a href>link<</a>

I have a jQuery script that swaps out a div when a href="#1" is clicked. The same link, a href="#1", is then replaced by a href="#2" and vice versa. Here is the jQuery code: $('.child2, a[href="#1"]').hide() $('#replacepagelinks a').c ...

When an Axios response is received, the console logs an error message

Whenever I try to console.log(response) from json placeholder, an error message pops up stating that there is an "Unexpected console statement". Below is the code snippet: import axios from 'axios'; export default { name: 'app', ...

Ways to expand the capabilities of Google Analytics for tracking AJAX requests and more, as recommended by the H5BP documentation

I need assistance with installing the Google Analytics enhancements mentioned in the extend.md file of H5BP (https://github.com/h5bp/html5-boilerplate/blob/v4.3.0/doc/extend.md). The documentation mentions using a specific code snippet for optimized Googl ...

Customizing data attributes for child components in Vue 2

In my Vue project, I have created a multi-page questionnaire using the v-show directive within a container called RiskAssessmentTest.vue. To handle loading questionnaire drafts, I have a component named RiskAssessmentDrafts.vue, which has the following st ...

New behavior in Vue 3: defineEmits is causing issues with defineProps data

Currently, I am working with Vue 3 and TS 4.4. In one of my components, I am using defineProps to define prop types. However, when I try to add defineEmits, VS Code starts indicating that my props variable is not recognized in the component template. Below ...

Web Page Content Scrambling/Character Exchange

I've encountered a perplexing issue that seems to strike randomly, yet I've managed to replicate the problem on three different desktops. Oddly enough, some other desktops never experience this issue and I'm at a loss as to what could be cau ...

Vanishing Tooltip following an implementation of the backdrop-filter

I'm having an issue with the blur effect on my background image. Although it works well, my tooltips also end up being blurred behind the divs: https://i.stack.imgur.com/BMdh4.png Is there a way to ensure that my tooltips stay on top of the subseque ...