Running a function of a component from within another component

In order to prevent any clutter and avoid using "native" jQuery/javascript, my goal is to elegantly call a function in the child component from the parent. The specific function I want to execute is change_map_data() from the child component G_Map.vue, all done in a Vue-like manner:

Parent.vue

<template>
<div class="col-md-12">
    ...
    <i v-on:click="change_map_data">change markers</i>
    ...
    <g-map v-bind:map_data="init_data.map"></g-map>
    ...
</div>
export default {
    data() {
        return {
            init_data: {
                map: {
                    map_ele: 'map'
                }
            }
        }
    }
}
</script>
</template>

G_Map.vue:

<template>
    <div :id="map_data.map_ele" class="gmap"></div>
</template>

<script>

import init_map from '../../../assets/js/map.js';

export default {

    props: ['map_data'],
    methods: {
        change_map_data: function() { // this function should be executed from the parent
            alert();
        }
    }
}
</script>

Answer №1

To execute a method defined on a child component from the parent component, you will first need to obtain a reference to the child component and then call its method directly:

<i v-on:click="$refs.map.change_map_data()">change markers</i>
<g-map v-bind:map_data="init_data.map" ref="map"></g-map>

If you are dealing with a dynamic number of maps, the process will be slightly different:

<div v-for="map, i of maps">
  <i v-on:click="$refs.map[i].change_map_data()">change markers</i>
  <g-map v-bind:map_data="map" ref="map"></g-map>
</div>

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

Using jQuery date picker to only allow selection of Sundays that fall on even weeks

Is there a way to disable Sundays if it is an even week of the year using this code? function settings(date) { if (date.getDay() == 0) { return [true, "", "Works"]; } else { return [false, "", ""]; } } $i("#searchsectionbari ...

Revised: "Mastering the Art of using useLoaderData Properly with Remix V2

It seems that the correct way to type useLoaderData has changed since V2. export const loader = async () => { return json({ messages: [...] }) } // In component... const { messages } = useLoaderData<typeof loader> Prior examples show it type ...

Guide to bringing in a JavaScript library from CDN links in a node.js script

Every time I want to run my script named myscript.js, I typically use this command: $ node myscript.js Is there a way for me to link the JStat Library into my script using the CDN address below: //cdn.jsdelivr.net/jstat/1.2.1/jstat.min.js ...

Dynamic TextField sizing

I am currently facing an issue while displaying data on a webpage using TextField component from @material-ui. Each record of data has varying lengths, making most values appear unattractive (occupying only 10% of the textfield width). Even though I am ut ...

What steps can I take to resolve the glitching issue with my progress bar?

There seems to be a problem with the progress bar lagging behind. To see the issue in action, click on THIS LINK and go to the second song. The progress bar appears to be malfunctioning. If you have any solutions or suggestions, please assist! For a visual ...

Error: The function m.easing[this.easing] is not defined

I have been working on creating anchor link scrolling and tooltip display using bootstrap, but I am encountering an issue. $(window).scroll(function(){ if ($(window).scrollTop() >= 100) { $('#header').addClass('fixed'); ...

Blur-triggered form validation

Within my webpage, I'm facing an issue with 5 input fields that need to be validated on blur. Instead of relying on alert boxes, I aim to display either an error or success message through DOM scripting. Despite trying various codes, nothing seems to ...

What is the best way to use jQuery AJAX to make changes to an HTML element that will be permanent even after the page is refreshed?

Starting out with codeigniter, I am working on building an ecommerce website. Every time a user clicks the "Add to cart" button in my view, I utilize jquery ajax to send a request to a controller function. This function then returns two variables: count ( ...

Utilizing autosuggest in combination with jQuery ajax consistently generates suggestions with a delay of 1 keystroke

I'm currently working on creating an autosuggest feature for a search box, but I've run into a problem. The suggestions that are displayed don't seem to match the current keystroke input (they keep showing suggestions based on the previous k ...

Enhance Your Vue3 Experience with Type-Safe Axios Requests

I have been exploring the concepts of "type safety" in my project using Vue3, TypeScript, and Axios. Although it seems straightforward, I can't shake the feeling that I am overlooking something obvious! To start off, I defined an interface called Bo ...

Simple Steps to Convert an HTML String Array into Dynamic HTML with AngularJS Using ng-repeat

Below is an array consisting of HTML strings as values. How can I convert these strings into executable HTML code to display them? [ {html:'<button>name</button>'}, {html:'<table > <thead> <tr> <th>#</ ...

randomly create a value that is not already included in the

I need help creating a random number that is not included in a specific array of numbers. JavaScript Solution: var restricted = [3, 4, 7]; function getRand () { rand = Math.floor(Math.random() * 10); if ($.inArray(rand, restricted) === -1) { ...

Is there a way to find all records created at a particular time daily through a query?

I understand how to search for documents within a particular range, but I am unsure of the query needed to retrieve all documents in a collection that were created at 3PM. Assuming there is a field called createdAt where this information is stored as Jav ...

Navigating a group of records in MongoDB

As a newcomer to MongoDB, I've set up two collections: "groups" for group information and "groupUsers" to establish user-group relationships. Currently, my goal is to retrieve all groups that the current user belongs to and then store this informatio ...

Express string declaration in a single TypeScript line

const restrictString = (str: string): string => str.match(/[ab]/g)?.join('') || '' Is there a way to restrict a string to only contain the characters 'a' and 'b' in a one-liner function? I am aware that this can ...

Unable to display data retrieved from JSON file

I am encountering an unusual issue while trying to retrieve elements from JSON in JavaScript. I fetch a JSON string from a URL using the following code: // Create Request HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"www.someurl ...

HighStocks should show categories instead of dates

The zoom function in HighCharts is what drew me to it initially. Everything was working perfectly until I encountered an issue that I can't seem to resolve. Here's my code snippet: http://jsfiddle.net/ma50685a/16/ $(function() { // Crea ...

Tips for monitoring user preferences across pages

Utilizing JavaScript, I have successfully hidden the site map on every page of the website to ensure accessibility for browsers with disabled JavaScript. By implementing a JQuery toggle function, users can easily reveal the Site Map by clicking on a design ...

Creating a 2D array of multiplication tables using JavaScript

My current task involves creating a program that generates a multiplication table for a given variable 'n'. The results must be stored in a two-dimensional array and displayed in the console with proper data formatting. Although I am familiar wit ...

Attempting to achieve dynamic text changes in the Bootstrap dropdown button based on the selected item

I am currently using Bootstrap to style a dropdown button, and I want the button text to change based on the item selected from the dropdown. I believe that using JavaScript is the most effective way to achieve this, but I am not very familiar with it ye ...