Retrieve the component information from the JavaScript function located outside of the main code

Is there a way to retrieve the component data using an external JavaScript function? I am looking to access markers, labels, and images.

Vue.component('home', {
        template: '#home',
        data: () => ({
            markers: [],
            label: '',
            image: ''
        }),
        // Life-cycle methods
        created() {
            document.title = 'home';

            ref.onSnapshot(snap => {
                snap.docChanges().forEach(change => {
                    const { type, doc } = change;

                    if (type == 'added') {
                        addMarker(doc.id, doc.data()); // Call Method
                    }
                });
            });
        }
    });

// Function outside the Vue.component (within the same file)

function addMarker(id, data) {
    let m = new gm.Marker({
        map,
        animation: gm.Animation.DROP,
        position: data.position,
        label: data.label,
        image: data.image // Custom
    });

    markers.push(m); // Access Component Data - markers

    m.addListener('click', e => {
        label = m.label; // Access Component Data - label
        image = m.image; // Access Component Data - image
        info.open(map, m);
    });
}

Answer №1

If you want to include the component instance in your function, simply pass it as an argument like this:

// Inside the component
created() {
    ...
    addMarker(this, doc.id, doc.data())
    ...
}

// External function definition
function addMarker(vm, id, data) {
    ...
    vm.markers.push(m)
    ...
}

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 the most effective method for identifying duplicate values in a multidimensional array using typescript or javascript?

I have a 2D array as shown below: array = [ [ 1, 1 ], [ 1, 2 ], [ 1, 1 ], [ 2, 3 ] ] I am looking to compare the values in the array indexes to check for duplicates. For example array[0] = [1,1]; array[1] = [1,2]; array[2] = [1,1]; We can see that ...

React Hook Form is experiencing an excessive amount of re-renders which can lead to an infinite loop. React sets a limit on the number

Currently, I am working on displaying a field named party. Once this field is selected, a list of products should be rendered. In my project, I am using React Hook Form along with the watch hook to keep track of changes. <FormProvider {...methods}> ...

What is the best way to animate an element to slide down when it is hidden with

I'm working on an html tag called "loginBox" (<loginBox> ... </loginBox>) that is initially hidden with display:none. When a user selects an option, I want it to smoothly slide down instead of just appearing and disappearing. How can I ach ...

Having difficulty communicating with the smart contract using JavaScript in order to retrieve the user's address and the balance of the smart contract

Hi there, I am a newcomer to the world of blockchain technology. Recently, I created a smart contract designed to display both the contract balance and user data, including the address and balance of the user. The smart contract allows users to deposit fun ...

Issue: req.flash() not functioning correctly following the execution of req.session.destroy()

In order to log the user out and redirect them to a login page with a message under specific conditions, it is necessary to destroy the user's current session. I usually use the flash feature to display a one-time message in my application, which work ...

A dynamic input field will appear on the page following the closing </form> tag

I encountered an unusual situation where upon clicking a button with the id #fusk, dynamic elements are added. Here is the code snippet: $('#imgc').append( "<div class='divi'>" + "<input type='hidden' name=' ...

Replicate styling while copying CodeMirror code

Is there a way to maintain the styling and formatting of javascript code when copying from CodeMirror? Whenever I try to copy and paste from the CodeMirror editor, the coloring and style are lost, with the content pasted as text/plain. How can I preserve ...

The error message "VueRouter does not have a property named 'history'" is common in Vue with TypeScript

In my typescript vue application, I encountered an error within a component while trying to access a parameter passed into the route. Here is the relevant code snippet: properties = getModule(PropertiesModule, this.$store); mounted() { id = this.$router. ...

Struggling to remove chosen indices from a list using Vue.js

I'm currently struggling with a major challenge involving deleting selected indexes from a list. I've attempted using the splice method and Vuejs delete() function, but so far, I haven't been able to make it work. Here's a snippet of w ...

Canvas flood fill is having trouble reaching the edges

While utilizing a flood fill algorithm to fill circles drawn on the canvas, I've encountered an issue where the algorithm fails to fill right up to the edge of the circle. Here is the implementation of the algorithm based on this blog post: function ...

A guide on personalizing HTML for Django forms

I have implemented an HTML template on my website and need to capture information for my Django backend. Specifically, I am trying to extract the email address from this section of code: <input type="text" placeholder="Email" value="" style="height: 30 ...

Is it necessary to delay until the entire page finishes loading in Selenium 3?

public boolean CheckPageLoadStatus(){ final ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() { public Boolean apply(final WebDriver driver) { return ((JavascriptExecutor) driver).executeScr ...

Exploring Tmbd Movie Database with React.js - Results of searches will only display after the application is recompiled

Presented here is my component. The challenge I am facing pertains to the fact that upon entering a search query, no results are displayed until I manually save in the code editor and trigger a recompilation of the application. Is there a more efficient ap ...

What is the best way to set the page title on a server-rendered component when using the Next.js app router?

When loading a blog post from the server, I have access to details like the title of the post. However, based on the app router migration guide, this information is located outside my page. How can I update it? For more information, refer to the documenta ...

Remove the "x" character from the phone field if an extension is not provided in the Jquery masked input plugin

Currently utilizing the jquery Masked input plugin. The mask I have applied to a field is as follows: "?999-999-9999 x9999" Why is there a ? at the beginning? This was implemented to prevent the field from clearing out when an incomplete number is ente ...

Mastering the art of nested await functions in JavaScript

In my current Nodejs application using mongoose, I am implementing cache with MongoDB in-memory and MongoDB database. This setup is running on Nodejs 8.9 with async/await support enabled. let get_func = async(userId) => { let is_cached = await c ...

having trouble transferring the password field in PHP to phpMyAdmin

My HTML form collects the user's first name, last name, username, and password. I am trying to upload this data to my local phpMyAdmin, but I'm facing an issue with storing the password in the database. Below is my HTML code: <input type="te ...

Developing object instances using AngularJS

Looking for some guidance on creating an object using Angular's factory capabilities since I'm new to AngularJS. Here's the code snippet that I have: angular.module('7minWorkout') .factory('WorkoutPlan', function(args){ ...

Utilize jQuery to select the parent checkbox and mark it as checked

Currently, I am working on a JavaScript function that will automatically check the parent checkbox if a child checkbox is checked. I am implementing this using jQuery and here is my HTML code: <ul id="ulParent" style="margin: 0; padding: 0; list- ...

How can I adjust the vertical position of Material-UI Popper element using the popper.js library?

https://i.stack.imgur.com/ZUYa4.png Utilizing a material-ui (v 4.9.5) Popper for a pop-out menu similar to the one shown above has been my recent project. The anchorElement is set as the chosen ListItem on the left side. My goal is to have the Popper alig ...