Is there a way for me to display a different value outside of the method by setting the variable?

Hello my dear friends.

I have a Vue data variable set up like this:

var comp=
{
    data()
    {
        return{
            polygonString:""
        }
    }
}

The issue I am facing is that when trying to update the 'polygonString' inside the 'modifyend' method, it remains blank when checked with console.log() outside the method:

methods:{
     addCoordinate(){
         modify.on('modifyend', function (evt) {

            var flat_coords;
            var modified_coords = [];

            evt.features.forEach(function (feature) {
            flat_coords = feature.getGeometry().getCoordinates();

            for (var i in flat_coords) 
            {
                var flat_coord = flat_coords[i];
                for(var coord_array in flat_coord)
                {
                    var lat_lng = flat_coord[coord_array];
                    var transformed_coords = ol.proj.transform(lat_lng,'EPSG:3857','EPSG:4326');

                    modified_coords.push(transformed_coords.toString().replace(",", " "));
                            }
                        }
                    });
                    this.polygonString = modified_coords.toString().replaceAll(",", ", ");
        });
        console.log("UPDATED POLYGON STRING:", this.polygonString);
     }
}

Answer №1

It appears that registering the modifyend event listener within a method could pose some challenges. It might be advisable to relocate the registration code to either the mounted or created lifecycle hooks.

To implement this adjustment, consider the following modifications:

mounted() {
  modify.on('modifyend', this.addCoordinate);
},
methods: {
  addCoordinate(evt) {
    var flat_coords;
    var modified_coords = [];

    evt.features.forEach(function(feature) {
      flat_coords = feature.getGeometry().getCoordinates();

      for (var i in flat_coords) {
        var flat_coord = flat_coords[i];
        for (var coord_array in flat_coord) {
          var lat_lng = flat_coord[coord_array];
          var transformed_coords = ol.proj.transform(lat_lng, 'EPSG:3857', 'EPSG:4326');
          modified_coords.push(transformed_coords.toString().replace(",", " "));
        }
      }
    });
      
    this.polygonString = modified_coords.toString().replaceAll(",", ", ");

    console.log("POLYGON STRING", this.polygonString);
  }
}

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

Leveraging Toaster Notifications in AngularJS for Custom Exception Management and Logging

Implemented the use of AngularJS Toaster for effective notification handling. To customize exception handling, set up in index.html as shown below <toaster-container toaster-options="{'time-out': 3000, 'position-class': 'toast ...

Steps for creating new users using a post request

I've been working on developing a chat application using react-chat-engine, and everything is running smoothly except for one issue - I'm struggling to figure out how to send a post request to create new users. Below is the code snippet I'v ...

Node.js dilemma of handling numerous asynchronous calls

As someone who is still learning the ins and outs of node.js, please bear with me. My goal is to cycle through an array of servers and assign a maximum of 60 tasks to each one. The number of incoming tasks can vary between 10 and 200. My intention is to a ...

Leverage Vue3's v-html feature without the need for additional wrapping tags by using script

Is it possible to use Vue's v-html directive within a Vue 3 <script setup> setup without needing an additional wrapping tag? I am looking to achieve something similar to the following: <script setup> const html = ref(`<pre></pre& ...

Unlocking the Power of Ajax for Displaying Wordpress Queries

Running into some issues trying to use jQuery for displaying content. I have set up three buttons that, when clicked, load data from a php file on my server. Everything functions properly except when attempting to retrieve Wordpress posts. An error message ...

What is the best way to transform this functioning JavaScript code into jQuery?

<script type="application/javascript" language="js"> function checkPasswordUpdate(value) { if(value === '1') { var nav = document.getElementById("sNav"); if(document.getElementsByTagName) ...

Using the set() method in Firestore with the merge option does not function properly when implemented in Node.js

const user = {name : myUsername}; databaseRef.set(user, { merge: true }); An error is occurring which states: Invalid use of type "undefined" as a Firestore argument. Despite following the Firebase documentation here, and seeing others use it in online ...

How to Re-run an External JavaScript File when React Conditional is updated?

Kindly review the complete question before providing an answer. I am currently working with a vanilla javascript file to trigger a fetch request upon pressing a button in a separate react file. The vanilla javascript file is located outside the src folder ...

What encodings does FileReader support?

Are you looking to easily read user-input files as text? If you can count on modern browser usage, then using FileReader is the way to go (and it works exceptionally well). reader.readAsText(myfile, encoding); It's worth noting that encoding defaul ...

What is the best way to create JavaScript code specifically for devices with a maximum width of 520px?

Is there a way to apply this JavaScript code specifically to devices with a maximum width of 520px? I could use some guidance on how to achieve this. // Apply code for max-width = 520px const myBtn = document.getElementById("darktheme"); const ...

Dealing with submit errors in React Redux forms

I am facing a challenge with handling exceptions properly when submitting in redux forms. I want to display a toast message when an error occurs. LogIn.js: class LogIn extends PureComponent { onSubmit = (values) => { const { login } = this.props; ...

creating a JSON array within a function

I am currently developing an Angular application and working on a component with the following method: createPath(node, currentPath = []){ if(node.parent !==null) { return createPath(node.parent, [node.data.name, ...currentPath]) } else { retu ...

Eliminate disparity in Woocommerce shopping cart

I have a pizza with various toppings. When the user selects "Add Toppings," they appear as drop-down options defaulted to "none." I want to hide the selected "none" options in the cart and checkout. Although I've successfully hidden them on the cart ...

Steps to automatically logout the user when the cookie expires in Nuxt

I have successfully implemented login functionality using the official NuxtJS Auth Routes example in my project with express-sessions. This is the content of my app.js file: const express = require('express') const session = require('expre ...

Is it possible to merge several blobs into one zip file using JSzip?

When attempting to download multiple images as a single ZIP file, the result is receiving separate zip files instead. The console log shows that the 'urls[]' array contains different arrays. const fileURLs = window.URL.createObjectURL(result);// ...

Dynamically loading an AngularJS controller

I am faced with the challenge of integrating an Angular app with dynamically loaded controllers into an existing webpage. Below is a code snippet where I have attempted to achieve this based on my understanding of the API and some research: // Create mod ...

"Webpack error: Including a comma within a string leads to a syntax problem when bund

I'm attempting to merge this file into my main JS. var constants = { height: 600, width: 400, default_bezier = "[ { \"startPoint\" : [51.6503017608354,203.464445873753], \"endPoint\" : [-52.41285540263849,202.372456432 ...

Delay problem caused by setTimeout

I am developing a version of the "Game of Life" using javascript. I have successfully implemented all the logic within a function named doGeneration(). When calling this function repetitively from the console, everything works as expected. However, when at ...

How to display an unordered list horizontally in HTML

I'm working on a screen that has filters displayed vertically, but I want to align them horizontally and have the filter options arranged in two columns. I've tried using CSS properties like spacing, clear, and display block, but the checkboxes/l ...

Encountering TypeScript errors with React-Apollo when using GraphQL to pass props to a higher order component

I've encountered some challenges while attempting to link a React class component with my local Apollo cache data. Following the guidelines outlined here, I have run into issues where VSCode and Webpack are generating errors when I try to access data ...