How to initialize data in Vue.js components

I'm working on a Map.vue component and I need to update its data in Vue.js. However, I'm struggling to figure out how to do this:

<template>
  <div>
    <div class="google-map" :id="mapName">
    </div>
  </div>
</template>
<script>
export default {
  name: 'google-map',
  props: ['name'],
  methods:{ 
    updateCurrentPosition(){
      navigator.geolocation.getCurrentPosition((position) => {
        this.$data.currentLocation = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };
        console.log("After setting, This.currentLocation = ");
        console.log(this.$data.currentLocation);

        this.map.panTo(new google.maps.LatLng(this.$data.currentLocation.lat, this.$data.currentLocation.lng));
        this.map.setZoom(18);
      });      
    },  
    initializeMap(){
      this.updateCurrentPosition(); 

      console.log("Before Marker, This.currentLocation = ");
      console.log(this.$data.currentLocation);

      this.addMarker(this.$data.currentLocation);
    },
    addMarker(LatLngObj){
      console.log("In addMarker This.currentLocation = ");
      console.log(this.$data.currentLocation);  

      var marker =  new google.maps.Marker({
        position: new google.maps.LatLng(LatLngObj.lat, LatLngObj.lng),
        map:this.map,
        icon:'http://www.magic-emoji.com/emoji/images/619_emoji_iphone_ok_hand_sign.png'
      });
    }
  },
  data: function () {
    return {
      mapName: this.name + "-map",
      markerCoordinates: [{
        latitude: 51.501527,
        longitude: -0.1921837
      }, {
        latitude: 51.505874,
        longitude: -0.1838486
      }, {
        latitude: 51.4998973,
        longitude: -0.202432
      }],
      map: null,
      bounds: null,
      markers: [], 
      currentLocation:{}
    }
  },

Although this.$data.currentLocation is correctly set in updateCurentPosition(), it appears as a blank object outside of that function. How can I ensure its value remains accessible from other functions?

Answer №1

Instead of using this.$data.currentLocation, use this.currentLocation.

You might have gotten confused by the

data () { return { currentLocation: null } }
object, which instructs vuejs to include currentLocation in its reactivity system.

However, all properties declared in this data object can be accessed directly using this.

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

HTML and JavaScript: Struggling to include multiple parameters in onclick event even after escaping quotes

I am struggling to correctly append an HTML div with multiple parameters in the onclick function. Despite using escaped quotes, the rendered HTML is not displaying as intended. Here is the original HTML code: $("#city-list").append("<div class='u ...

Error code 70006 encountered in Typescript when attempting to reference a type as "any"

Currently, I am working on a React project that involves using TypeScript. This is quite new to me, and I have encountered a type error in one of my components... let dragStart = (e) => { let transferringData = e.dataTransfer.setData("text", e.tar ...

Having trouble launching the Socket.io Chat Demo? Encounter an issue with the error message at ..//

Hello, I am a novice in the world of programming and recently attempted to run the socket.io chat demo. Unfortunately, I encountered an error message at line 5 stating that it cannot find ('../..'). Can someone please shed some light on why this ...

Struggling to make a form submit work with AngularJS and a Bootstrap datetime picker

Struggling to create a post and include name and datetime using a bootstrap datetimepicker. After selecting the datetime and clicking add, nothing happens. However, if I manually type in the field and click add, it submits successfully. Despite reading up ...

Exploring the syntax of Vue's data function

I encountered a syntax error while compiling my assets: Syntax Error: SyntaxError: C:\xampp\htdocs\dtcburger.com\resources\js\components\stripe\STRIPEform3.vue: Unexpected token, expected ";" (51:12) 49 | { ...

What is the most efficient way to find the maximum, minimum, and median values in an array?

[ 0: {"carrier": "Spicejet", "value": 2596}, 1: {"carrier": "Spicejet", "value": NaN}, 2: {"carrier": "Spicejet", "value": 2864}, 3: {"carrier": "Indig ...

Fields are now being tagged with the q-field-no-input flag

Has anyone encountered the issue of the q-field-no-input class being added to fields even when there is an input inside them? It's causing a strange margin that disrupts the formatting across all my pages. I'm hoping to understand why this class ...

What is the best way to send the index variable to an HTML element in Angular?

Is there a way to pass the index variable to construct HTML in the append() function? .directive('grid', ['$compile', function(compile) { return { restrict: "E", scope: { elements: '=' ...

``The background color will dynamically change according to the result of a function

My function named shift_color generates different color codes like "#FF5F74", "#5FFF66", and "#5F8AFF". I am looking to use this output to style a navigation menu background. I have tried the following code: .topnav { background-color: <?php echo shi ...

chaotic telerik editor arrangement

I have incorporated the Rad Editor into my ASP.NET page. <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <telerik:RadEditor ID="reSummery" runat="server" > </telerik:RadEditor> Despite not referencing ...

Encountering the error "undefined object" while using the yield keyword in JavaScript

var pi = document.getElementById("pi"); function * calculatePi(){ let q = 1; let r = 0; let t = 1; let k = 1; let n = 3; let l = 3; while (true){ if (4*q+r-t < n*t){ alert(n); yield n; ...

What is the best way to segregate Express routes from server.js?

I've been closely following a Vue SSR guide on GitHub and noticed that the author has organized their Express routes within a file named server.js. For better organization, I prefer to keep my Express routes in a file called router.express.js located ...

Removing the previous value in React by shifting the cursor position - a step-by-step guide

I have successfully created a phone using React that saves the numbers in an input field whether you press the keys or use the keyboard. Although the phone is functioning well, I am facing an issue where pressing the delete button or backspace key always ...

Using a For Loop in VueJS with TypeScript for an array of objects

I'm currently working on a for loop within an object array. Below is the code snippet I am working with: private async rightsOverview() { let item: any[] = []; const prod = await fetchFromApi<ProductionBaseType>(`/productions/${id ...

Comprehending the inner workings of the reduce() method

After spending hours reading and watching videos to understand the reduce function, I finally had a breakthrough. It wasn't until I took a break, made some food, and came back to my computer that it all clicked. Now, I confidently grasp how the reduce ...

Persistence of query parameters from old routes to new routes using vue-router

Whenever a query parameter called userId is present in a route within my application, I want the subsequent routes to also include this query parameter. Instead of manually modifying each router-link and router.push, I am looking for a solution using rout ...

encountering a problem with retrieving the result of a DOM display

private scores = [] private highestScore: number private studentStanding private studentInformation: any[] = [ { "name": "rajiv", "marks": { "Maths": 18, "English": 21, "Science": 45 }, "rollNumber": "KV2017-5A2" }, { "n ...

When utilizing npm install buefy and npm install font-awesome, there may be an unnecessary display of [email protected] and [email protected] extraneous errors

After installing buefy and font-awesome, I noticed that it is marked as extraneous and the folder appears with an arrow icon but is empty. How can this issue be resolved? For example: +-- <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Text input in Bootstrap not reaching full width

Trying to achieve a Bootstrap textfield embedded in a panel that spans 100% of the remaining space-width within the panel. However, this is the result obtained: The blue border represents the edge of the panel. Below is the code being used: <div clas ...

Tips for Retrieving the Key Names of JSON Objects within a JSON Array

I'm trying to retrieve the object names "channelA" and "channelB". Here is the JSON data: [ { "channelA": { "programmes": [ { "start_utc": 1522208700, "stop_utc": 152220 ...