Create a new variable to activate a function within the parent component in Vue

I want to invoke a function in the parent component from its child component.

In my Vue project, I have designed a reusable component that can be used across multiple pages. After the function is executed in this component, I aim to call a specific function in its parent element.

To achieve this, I utilize this.$parent.getLocations(), which effectively triggers the desired function.

However, since the component should be flexible and adaptable, the function name needs to be dynamic - for instance, it could be getPets() or getLunch().

I pass the keyword 'Location' through as a prop, enabling me to use it within the component. But when attempting expressions like

'${this.$parent}.get${this.type}s()}'
(where this.type is 'Location') or
this.$parent + ".get" + this.type +" s()
', the functions fail to execute properly.

How do I set `getLocations` as a variable to run the specified function?

Answer №1

Avoiding an anti-pattern is crucial. It's best practice for a child component not to be aware of its parent's functions.

Example in the child component:

this.$emit('needs-locations', { type: this.type })

And in the parent component:

<child @needs-locations="getLocations" :locations="locations">

getLocations(type) {
  api.then((locations) => this.locations = locations)
}

This approach allows for bidirectional communication between components without creating dependencies.

Answer №2

Start by dispatching an event from the child component to its parent and include a specified type.

this.$dispatch('executeAction', type)

Next, handle the dispatched event:

<child @executeAction="handleExecution"/>

In the parent component, the method for handling the action would be as follows:

handleExecution(type) {
        switch (type) {
            case 'Tasks':
                performTasks();
            case 'Chores':
                completeChores();
            default:
                break;
        }
    }

An alternative approach using if-else statements can also be used effectively.

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

Content moves as you scroll, not within a lightbox

I have implemented lightbox style overlays for my 'Read More' content on my website. However, I am facing an issue where the content within the lightbox does not scroll; instead, the background page scrolls. Any assistance with resolving this p ...

When executing an $http get request in Angular, a promise is

After implementing this code in my service and noticing that it works, I have a question. Since $http.get() returns a promise which executes asynchronously, I am confused about why I need to use deffered.resolve(res.data) to return data in my service. Yo ...

Guide on extracting an Array from JSON in a $.ajax response

I received a JSON value that was converted from an array in the AJAX response. {"Text":"Please provide a value","Email":"Please provide a value"} My goal is to extract the response JSON and display it within a div using $(div).html(): Text-Please provid ...

Don't forget the last click you made

Looking for a way to style a link differently after it has been clicked and the user navigates away from the page? Check out this code snippet I've been using: $(document).ready(function(){ var url = document.URL; function contains(search, find) { ...

Issue with Material-UI: Unforeseen TypeError arises while toggling between two Drawer elements

Note: I am utilizing material-ui 3.3.0 My goal is to have two <Drawer> components displayed on a page, with one sliding in from the left and the other from the right. In an <AppBar>, there are two <Button> components that toggle the visi ...

How to use JavaScript and regex to control the state of a disabled submit button

I have a challenge where I need to activate or deactivate a submission button in a form called btn-vote using JavaScript. The button will only be activated if one of the 10 radio buttons is selected. Additionally, if the person-10 radio button is chosen, t ...

Exploring how to read class decorator files in a Node.js environment

I've developed a custom class decorator that extracts permissions for an Angular component. decorator.ts function extractPermissions(obj: { [key: 'read' | 'write' | 'update' | 'delete']: string }[]) { re ...

Generate a randomly structured 2D array called "Array" using JavaScript

Can anyone help me with extracting a random array from a 2D named array? I've tried several solutions but none of them seem to work. var sites = []; sites['apple'] = [ 'green' , 'red' , 'blue' ]; sites['o ...

Working with both vue 2 and vue 3 simultaneously on a single machine

Starting my first vue 3 project and running into issues with installing vue-cli. The documentation mentions that for Vue 3, I should be using Vue CLI v4.5 which can be found on npm as @vue/cli. To upgrade, it is necessary to reinstall the latest version of ...

The ng-repeat function in AngularJs does not display the data despite receiving a successful 200 response

As part of my academic assignment, I am exploring Angularjs for the first time to display data on a webpage. Despite receiving a successful http response code 200 in the Chrome console indicating that the data is retrieved, I am facing issues with displayi ...

Heroku Node.js - Cross-Origin Resource Sharing (CORS) is functioning correctly for all API requests except for when using the image upload

Our web application contains numerous APIs that retrieve data from a Node.js server deployed on Heroku. Most of the APIs function correctly, with the exception of one that allows users to upload images to the server. While this API worked flawlessly in o ...

The JavaScript object is not being properly posted to the $_POST variable on the PHP page when using vanilla AJAX

Despite my extensive search on the internet and stackoverflow, I have yet to find a solution to my problem. While I understand that JQuery is effective in sending objects, when attempting the same task without the framework, my posts fail to go through to ...

What is the process by which Node can access predefined variables in clustering?

Consider the following code snippet: var running = false; var cluster = require('cluster'); if(cluster.isMaster){ cluster.fork(); running = true; } If this code is executed within multiple forks, would the value of 'running' ...

Displaying JSON data dynamically by iterating through it in a loop

While working with JSON data in a loop, I noticed that the code quality does not meet my expectations. I have a feeling that I might be missing something in my approach. $(function(){ $.getJSON('data.json', function(data){ let content ...

Is there a way to trim the current shapes in three.js?

I have created a shape similar to this using Box Geometry at the following link: https://jsfiddle.net/cdu96z3c/. I am looking to achieve a design like the image below by properly utilizing v.x and v.z, while maintaining the current corrugation and properti ...

Struggling to Confirm Inaccuracies in Material UI Forms

Struggling to validate form errors in React with Material UI using JOI and running into issues. Even the console.log() results are not showing up in my validate function. The error display is also confusing. ... import React from "react"; import ...

Adding content to a text field and then moving to the next line

I am looking to add a string to a text area, followed by a new line. After conducting some research, here are the methods I have attempted so far but without success: function appendString(str){ document.getElementById('output').value += st ...

webstorm error: unresolved function or method when using npm azure-storage modules

Encountering a problem with WebStorm IDE when using azure-storage library as it is unable to find the correct methods for intelligent coding (although the code runs without errors). View image of unresolved function or method Appreciate any help you can ...

The "a" HTML link element is stubbornly resisting being attached to an event listener

I have implemented the MutationObserver observer in my program to monitor the addition of elements. One specific condition I am checking for is if the added element is an anchor tag (tag="a") and if the link is a DOI, then I attach a contextmenu ...

Ways to extract JSON data from multiple JSON arrays

Within the snippet below, I am attempting to extract the value of women. Right now, I can successfully retrieve 1. Personal care appliances and 2. Jewelry. However, if I try to check any checkbox after that, I encounter an error stating "Uncaught TypeError ...