Executing a method from a callback within the data() function in Vue 2.7 – Here's how!

This component uses a third-party module known as HelloWorld. This module has a prop called closeCallbacks, which is an array of callbacks that are triggered when the HelloWorld component is closed.

Unfortunately, the functionality of the third-party component cannot be modified.

To utilize the HelloWorld component in my template, I pass the closeCallbacks array from the data:

<template>
    <HelloWorld :closeCallbacks="closeCallbacks" />
</template>

Next, I create an array of callbacks in my data section. Each callback includes an 'action' property required by the HelloWorld component, which is invoked upon the closure of HelloWorld:

<script lang="ts">
export default defineComponent({
    data() {
        return {
            closeCallbacks: [
                {
                    action: function () {
                        return this.handleCloseCallback();
                    },
                },
            ],

        };
    },
    methods: {
        handleCloseCallback: function () {
        //
        },
    },
});
</script>

When the 'action' callback is executed, I intend to call the handleCloseCallback method of my component (as demonstrated above).

However, I encounter an error in Vue 2.7:

Property 'handleCloseCallback' does not exist on type '{ name: string; action: (item: any) => void; }'.

When I convert handleCloseCallback to an arrow function:

handleCloseCallback: () => {
            //
            },

I am presented with a different error:

Property 'handleCloseCallback' does not exist on type 'CreateComponentPublicInstance<{}, {}, {}, {}, {}, ComponentOptionsMixin, ComponentOptionsMixin, {}, {}, {}, false, OptionTypesType<{}, {}, {}, {}, {}, {}>, ... 5 more ..., {}>'.

So, my inquiry is: how can I invoke a method from a callback defined in the data section?

Answer №1

Is this the solution to your problem?

<template>
  <HelloWorld v-if="closeCallbacks.length" :closeCallbacks="closeCallbacks" />
</template>
<script>
export default defineComponent({
  data: () => ({
    closeCallbacks: []
  }),
  mounted() {
    this.closeCallbacks = [{ action: this.handleCloseCallback }]
  },
  methods: {
    handleCloseCallback() {}
  }
})
<script>

The key point to note here is that this.handleCloseCallback is defined in the mounted section, which is why it is not yet available when the data is being parsed.
I have used a v-if to delay the rendering of components until closeCallbacks is filled, preventing the component from being initially rendered with an empty closeCallbacks array.


I believe this is what Estus was recommending as well. Not only does it work, but I also find it to be a neater solution:

export default defineComponent({
  computed: {
    closeCallbacks() {
      return [{ action: this.handleCloseCallback }]
    }
  },
  methods: {
    handleCloseCallback() {}
  }
})

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

extracting data from json using javascript

Here is the data in JSON format var testData = {text: '{"status":200}'}; I am attempting to extract the status using this code: console.log(testData.text.status); However, it returns undefined Could you please provide guidance on how to succ ...

Include a new module in the declarations NgModule utilizing ts-morph

Currently, I am utilizing the ts-morph library and my objective is to add a new component to the declarations: This is my initial setup: @NgModule({ declarations: [], imports: [], providers: [], }) Here is what I am aiming for: @NgModule({ declarations: [ ...

What alternative can be used for jquery isotope when JavaScript is not enabled?

Is there a backup plan for jQuery isotope if JavaScript isn't working? For instance, if I'm using the fitColumns feature, is there an alternative layout style available in case JavaScript is disabled, similar to what is seen on the new Myspace? ...

What is the reason behind the absence of certain fontAwesome icons?

I'm having trouble connecting Font Awesome in Vue.js ************* import { library } from '@fortawesome/fontawesome-svg-core' import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome' import { faVuejs } from '@fortawesom ...

Prevent automatic refreshing of React app on remote devices

My friend and I are collaborating on the development and testing of a React app simultaneously. He accesses the app from my machine using my IP address but encounters an issue where every time I save something in the code, the app reloads on both of our ...

Is there a way to invoke a function using a variable in place of its actual name?

Check out my code snippet: $('.click').on('click', function(){ $.ajax({ url : $(this).siblings('a').attr('href'), dataType : 'JSON', success : function (tags) { $ ...

Issue with passing props from parent component to child component in Vue.js not functioning

As a newcomer, I have been assigned a project that involves using Vuejs. In this project, there is a page that utilizes a component called DashboardCard. Each DashboardCard receives 2 props - val and icon from the parent component. https://i.stack.imgur. ...

Empty refreshToken in aws-amplify's javascript

Utilizing aws-amplify, my configuration looks like this: Amplify.configure({ Auth: { region: config.aws.region, identityPoolRegion: config.aws.region, userPoolId: process.env.userPoolId, userPoolWebClientId: process.env.appClientI ...

Trouble with an external .js script

function displayMessage() { var isConfirmed = confirm("Do you want to proceed?"); if (isConfirmed) { window.location = "./proceed"; } }; function checkIfEmpty(){ console.log("checkIfEmpty"); }; @CHARSET "ISO-8859-1"; form { margin:0 auto; width:300px ...

Every time I invoke a module, non-global variables are utilized

Within a module.exports file, I am facing an issue where the variables are shared among different instances of the module. Instead, I want each call to the module to have its own set of values for cycle number, original data, new product, etc., similar to ...

The link.url in my code is consistently changing, while the pathName remains static

My code is experiencing an issue where link.url is changing but pathName is not. I am trying to implement an animation transition on my website, but it is not working correctly because the pathName and link.url do not match. "use client" import ...

The Jest worker has run into 4 child process errors, surpassing the maximum retry threshold

I am a newcomer to Vue and Jest testing, and I keep encountering this error when running a specific test. While I understand that this is a common issue, I am struggling to pinpoint the exact cause of the problem. Here is the error message: Test suite fa ...

Issues with Ionic 3 Directive Not Functioning

Struggling to create a custom directive in Ionic that won't resize automatically? I can't figure out what's going wrong. Here's the code snippet from my project, which is an Ionic 3 app with Angular 4: import { Directive, HostListener ...

An effective method for adding information to a REDIS hash

My current computing process involves storing the results in the REDIS database before transferring them to the main database. At the moment, I handle operations in batches of 10k items per chunk using a separate GAE instance (single-threaded computing wi ...

Exploring the power of Supabase's two-tiered joins using TypeScript

After reviewing the documentation here, I managed to successfully implement the first level join (agent_profile) but encountered issues when trying to join the next level (agent_office). Although the query returns the correct data, both VS Code and my app ...

What is the best way to transform this JSON data into an array of key-value pairs in JavaScript?

Dealing with nested JSON data can be challenging, especially when trying to extract key-value pairs efficiently. If anyone has suggestions on how to simplify this process and improve readability, please share your insights. The goal is to transform the ne ...

The error message in AuthenticatedLayout.jsx on line 43 indicates a problem with trying to access properties of an undefined object, specifically the 'name'

I am encountering this issue react-dom.development.js:26923 Uncaught TypeError: Cannot read properties of undefined (reading 'name') at AuthenticatedLayout (AuthenticatedLayout.jsx:39:55) AuthenticatedLayout.jsx import { useState } from "re ...

collection of assurances and the Promise.all() method

Currently, I am dealing with an array of Promises that looks like this: let promisesArray = [ service1.load('blabla'), service2.load(), // throws an error ]; My goal is to execute all these Promises and handle any errors that occur, as ...

Strategies for maintaining pristine Firebase child paths

I have a list of data that I want to structure in Firebase. However, I encountered an error: Error: Firebase.child failed: The first argument provided is not a valid path. Path names should not include ".", "#", "$", "[", or "]" characters and must be no ...

Enhance the functionality of jqGrid by customizing key bindings for arrow and tab keys

In order to enhance my jqGrid functionality, I am seeking to implement the ability for users to press different keys for specific actions. For example, pressing Enter should save data (which is currently working fine), while pressing the left arrow key sho ...