Step-by-step guide on triggering a parent component event from a child component in Vue3 programmatically

I am currently working on a Vue 3 project where I utilize a component named revogrid to build a dashboard. This particular component requires another component to render a cell as a parameter. My goal is to create an event within the child component that can change the value of the cell by modifying the parent component's datasource. How can I set up this event within the child component using code?

Here is the code snippet for the PARENT COMPONENT:

<template>
  <div id="home">
    <v-grid theme="material" row-size="48" readonly="true" :source="rows" :columns="aux" />
  </div>
</template>

<script>
import VGrid, { VGridVueTemplate } from "@revolist/vue3-datagrid";
import Task from '../components/Task'; 

export default {
  data() {
    return {
      aux: [],
      columns: [
        {
          name: "Company",
          prop: "company",
          columnType: "string",
          size: 150,
        },
        {
          name: "Advance",
          prop: "advance",
          size: 150,
          cellTemplate: VGridVueTemplate(Task),
        },
        {
          name: "Sefip",
          prop: "sefip",
          size: 150,
          cellTemplate: VGridVueTemplate(Task),
        }
      ],
    }
  }
}
</script>

In the above code, the Task component is included as a property within the columns array variable. What I aim to do is establish an event inside the Task component that can trigger a method in the parent component.

I attempted to achieve this with the following code:

Task.$emitter.on("update_cell", () => {
  alert("I am triggered from the parent");
});

However, this approach did not produce the desired outcome...

Answer №1

Finally, I have solved this particular requirement.

// Here is the default column configuration
{
    prop: 'columnAction',
    label: '',
    size: 75,
    minSize: 75,
    maxSize: 75,
    readonly: () => true,
    cellTemplate: VGridVueTemplate(EditableGridCellColumnAction),
}

If you want to pass custom props or emits, you will require

import { h } from 'vue';

and make some adjustments to the cellTemplate as shown in the sample below

{
    prop: 'columnAction',
    label: '',
    size: 75,
    minSize: 75,
    maxSize: 75,
    readonly: () => true,
    cellTemplate: VGridVueTemplate(

        h(EditableGridCellColumnAction, {
            onDeleteRow: payload => {
            console.info(payload);
            },
        })
    ),
}

Answer №2

When working in Vue3 with the Composition API, I was able to resolve the issue like so:

(this approach should also be compatible with Vue2)

Parent component modification:

[...]
const myFunction = () => {
   console.log("Hello World")
}

columns.value = [
  { prop: "foobar", size: 150 },
  {
    name: "my column",
    cellTemplate: VGridVueTemplate(MyComponent),
    prop: {
      myFunction: myFunction
    },
  },
]
[...]

In the child component (column):

[...]
// make sure that "prop" is defined within "props"
const props = defineProps(["prop"])


// execute the function using
props.prop.myFunction()

[...]

By executing the function within the parent component's scope, it gains access to all of its properties and methods.

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

Transferring data between Django and JavaScript: dealing with DateTime information

I'm facing an issue while attempting to transfer data (step_count_data) from Django to a JavaScript function. Below is the code snippet: Django #somecode step_count_date.append(str(step_count_list[i].startTime.date())) context = {'step ...

Unable to retrieve value 'includes' from null object

Currently, I am utilizing Vue.js along with JavaScript. In my code, there is an array of objects named products, each containing a special property called smallest_unit_barcode. My goal is to filter out only those products that have a barcode similar to a ...

Transferring information from a file to a displayed page in Sails.js

I have a challenge in my application where I need to read a large dataset and send it to the client for manipulation with D3.js. The issue is that loading such big datasets can be time-consuming. My solution is to implement streaming, but I'm not sure ...

Ways to address the issue of "$ is not a function"

Whenever I attempt to upload an image, this error message pops up: $ is not a function The source of the error can be found here: $(document).height(); ...

A series of OR interfaces in TypeScript Interface

Imagine a scenario where there is a choice between multiple interfaces interface a {x:string} interface b {y:string} interface c {z:string} type all = a | b | c Now, consider an object fulfilling all by being of type c When you try to access the propert ...

End the connection to mongodb within a callback function

I am currently diving into the world of mongojs and nodejs, still grappling with the concept of programming asynchronously. My goal for this program is to read input from a file ('list'), process each line by passing it through a parse function t ...

Ensuring that the keys in a JSON object match the expected keys using JavaScript and React

Looking at the JSON data provided below: [ { "name":"john", "school":"school 2", "address":"newyork" }, { "name":"peter", "school":"school 1", ...

Shifting Vue components within the dom structure?

Whenever I am on a mobile device, I move Vue components higher up in the dom so that I can use absolute positioning without being contained within a relative container. if (this.mobile) { this.$el.parentNode.removeChild(this.$el); document.getElem ...

Requesting an API token through the body using Javascript's Fetch function

I'm currently working on developing a frontend application using Javascript Fetch to interact with an API service. One of the tasks I need to accomplish is to create a token by using the POST method and sending an apiKey parameter in the Body. Once I ...

What is the correct method for asynchronously loading CSS files in web development?

On a mission to enhance my website's performance, I set out to achieve the perfect score on PageSpeed Insights. Everything was going smoothly until I encountered an issue with CSS delivery. I initially achieved a flawless result by utilizing the prel ...

Is there a way to trigger javascript on Amazon once the "Next Page" button is clicked?

My Greasemonkey script is designed to run on Amazon's search results page. However, I've noticed that when the "Next Page" button is clicked and new results are dynamically loaded, my script only executes once after the initial page load. Here&a ...

Tips on using MUI Texfield and Redux to update state

I am facing an issue with my input field as I attempt to pass some information before navigating to a different page. The problem lies in the fact that my Redux state is not updating, although the console confirms that the value is being passed correctly. ...

Encountering issues with compiling in Laravel due to an error in the app.scss file

Encountering an error log while executing npm run watch Laravel Version:- 5.6 Vue Js version:- 2.5.7 Details of the Error: pbdgr@DESKTOP-LRSJU17 MINGW64 /f/coding and website developing/Multipurpose vue js and laravel website/larastart (master) $ npm ru ...

Managing the state of dynamically generated tabs within a NextJS application

Looking to develop a web app in Next.js that includes tabs components. The goal is to manage various entities within each tab, such as utilizing a search bar to select different products. Upon selecting a product, a new tab will be generated with the produ ...

Using jQuery to load and parse a JSON file stored on a local system

I am a beginner in scripting languages and recently searched for ways to load and parse JSON files using jQuery. I found helpful resources on Stack Overflow. The JSON file I am working with is called new.json. { "a": [ {"name":"avc"}, ...

Managing a webpage using Xcode and Swift's UIWebView

Recently, I developed a straightforward application that guides users to a web-based platform. One of the app's pages allows users to search for store stock from various stores by manually inputting the store number or utilizing automatic location det ...

Issue with scroll being caused by the formatting of the jQuery Knob plugin

I am currently utilizing the jQuery Knob plugin and I am looking to have the displayed value shown in pound sterling format. My goal is for it to appear as £123456. However, when I attempt to add the £ sign using the 'format' hook, it causes is ...

Tips for confining the draggable div within its container

I've been working with React and TypeScript, and I recently added the W3School drag div example to my React app. However, I'm facing an issue where the draggable div is moving outside of the container. Can someone please guide me on how to confin ...

Ways to incorporate JSON web token into every query string of my requests

Just recently, I grasped the concept of using JSON web tokens. Successfully, I can generate a JSON web token upon sign-in and have also established the middleware to authenticate my token and secure the routes that fall under the JSON verification middlewa ...

I'm looking to send JSON data using jQuery's AJAX method - how can I

I was recently assigned a project with the following instructions: Develop an HTML page that will use our API endpoint to fetch a list of logs from our API logger and display them in a visually appealing grid. The page should automatically make this call e ...