Utilize data fields beyond the export default in Vue

Is there a way to access the information stored within the export default in my Vue component's JavaScript file? Specifically, I am trying to retrieve the contents of the routes array within the calculateAndDisplayRoute() function.

overview.js

function calculateAndDisplayRoute(directionsService, directionsDisplay) {
  var origin, dest;
  for (var route in this.routes /*<--HERE*/) {
    console.log('www')
    if(route.id == this.filter){
      console.log('true')
    }
  }
  directionsService.route({
    origin: 'Vancouver',
    destination: 'Chicago',
    travelMode: 'DRIVING'
  }, function(response, status) {
    if (status === 'OK') {
      directionsDisplay.setDirections(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
}

export default {
  name: 'fleet-overview',
  data () {
    return {
      view: '',
      routes: [], //<--HERE
      users: [],
      errorRoute: '',
      response: [],
      filter: 'searchby',
      searchTerm: '',
      users: [],

    }
  },
  created: function () {
    this.routeView();
  },
  methods: {
      initMap: function(){
        this.$nextTick(function(){
          var directionsService = new google.maps.DirectionsService;
          var directionsDisplay = new google.maps.DirectionsRenderer;
          var map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: 45.49, lng: -73.61},
            zoom: 9
          });
          directionsDisplay.setMap(map);
          var onChangeHandler = function() {
            calculateAndDisplayRoute(directionsService, directionsDisplay);
          };
          document.getElementById('filterselect').addEventListener('change', onChangeHandler);
        })
      }
//...
}

Answer №1

If you want to ensure the correct context is set in JavaScript, consider using call.

calculateAndDisplayRoute.call(this, directionsService, directionsDisplay);

Alternatively, you could modify the function definition to include a parameter for the context (instead of using this).

function calculateAndDisplayRoute(context, directionsService, directionsDisplay) {
  ...
  for (var route in context.routes /*<--HERE*/) {
    console.log('www')
    if(route.id == context.filter){
      console.log('true')
    }
  }
  ...
}

In your initMap function, pass this as the first argument:

calculateAndDisplayRoute(this, directionsService, directionsDisplay);

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

JSFiddle Functioning Properly, But Documents Are Not Loading

My JSFiddle is functioning properly, but the files on my computer aren't. It seems like there might be an issue with how they are linking up or something that I may have overlooked. I've checked the console for errors, but nothing is popping up. ...

The art of selecting elements and attaching event listeners in a React environment

Currently, I am working on my portfolio website using Gatsby. The layout includes a sidebar on the left with navigational links (Home, About, Work, etc.), and the main content is displayed as one long strip of sections on the right. When a user clicks on a ...

The double click functionality does not seem to be functioning within the Backbone View

I am trying to detect double click event within a Backbone view var HomePage = Backbone.View.extend({ initialize: function(){ this.render(); }, render: function(){ var template = _.template($('#app1').html()); ...

Updating meta tags dynamically in Angular Universal with content changes

Hello, I'm encountering an issue with a dynamic blog page. I am trying to update meta tags using data fetched from the page. Here's the code snippet: getBlogPost() { this.http.get(...) .subscribe(result => { this.blogPost = re ...

Translating Encryption from Javascript to Ruby

I have an application which utilizes HTML5 caching to enable offline functionality. When the app is offline, information is stored using JavaScript in localStorage and then transmitted to the server once online connectivity is restored. I am interested in ...

Combine various arrays of objects into one consolidated object

Problem: There are untyped objects returned with over 100 different possible keys. I aim to restructure all error objects, regardless of type, into a singular object. const data = [ { "type":"cat", "errors" ...

Is it possible to nest ng-repeat and access $first and $last properties simultaneously

Below is the form that I am currently working with, <tbody ng-repeat="attGroup in attributesGroups"> <tr> <td class="vcenter text-right"> &nbsp;&nbsp;<a href="javascript:" ng-click="!$last && up ...

Utilizing jQuery to Calculate Tab Scores

Last week, my teacher and I collaborated on a fun game called rEAndom game (). The game is created using javascript, jQuery, and HTML5. One interesting feature of the game is that when you press the TAB key, a div displaying the score appears. You can chec ...

The compatibility between JSON and the CORS header 'Access-Control-Allow-Origin' is crucial

I am trying to obtain the value from a JSON file that is located on the server. To retrieve this value, I am using AJAX. However, when checking the console for errors, I receive the following message: Cross-Origin Request Blocked: The Same Origin Poli ...

Looking to extract data from a Json object and add it into a table

<!DOCTYPE html> <html> <head> <script type="text/javascript"> function displayJsonData() { var jsonData = { "cars": [ '{"model":"Sentra", "doors":4, "features":["hi"," ...

playing with JSON data in angular

Currently, I am utilizing AngularJS and making use of $http.get to fetch a JSON response which I then assign to $scope.myObjects. After implementing ng-repeat="object in myObjects" in the HTML, everything seems to be functioning properly. My query pertai ...

Exploring Three.js: The challenge of loading multiple material objects

I am currently using three.js and facing an issue while loading multiple material objects. The problem arises when I rotate the code, causing unexpected behavior with the second material object. Ideally, I want the first material object [cubeMaterial] to r ...

Can users arrange a lineup of choices?

As a beginner, I have a task that seems pretty simple to others but not so much for me. I need to create a feature where a client can order 10 different services in the order they prefer. The idea is to use a dropdown menu or checkboxes to allow the user ...

Having trouble logging JSON data from nodejs + express while serving static files through express. However, I am able to see the data when I only make a GET request for the JSON data without the static files

Currently, I am experimenting with sending data from a nodejs + express server to the front-end static files. The objective is for JavaScript (allScripts.js) on the front-end to process this data. At this stage, my aim is to log the data to the console to ...

Numerous documents within a JavaScript application

As a newcomer to JavaScript, I've been experimenting with the language to enhance my understanding. One aspect that puzzles me is how developers organize large JavaScript programs. In languages like Java, breaking down code into smaller files is commo ...

Ways to receive a POST request from an external server on a GraphQL Server

Currently, I am working on a project that utilizes GraphQL. As part of the project, I need to integrate a payment processor. When a user makes a successful payment, the payment processor sends a POST request to a webhook URL that should point to my server. ...

Combine array elements in Angular/Javascript based on a certain condition

Is there a way to combine elements from two arrays while avoiding duplicates? array = [ {id: 1, name:'abc'},{id: 1, name:'xyz'},{id: 2, name:'text1'},{id: 2, name:'text2'} ]; The desired output is: result = [{id: ...

The inline script is deemed non-compliant as it infringes upon the Content Security Policy directive: "script-src 'self'"

My chrome-extension is built using react-create-app. However, I encountered an error when running npm run build in react-create-app: Refused to execute inline script because it violates the following Content Security Policy directive: "script-src &apo ...

Problem encountered when trying to use the sharp package in NuxtJS

I attempted to implement this code in my Nuxt project, but it encountered an issue during compilation. Within my plugin/sharp.js file: import vue from "vue" import sharp from "sharp" vue.use(sharp) And in my nuxt.config.js file: plugi ...

Add the component view to the webpage's body section

Using Angular 7 and ngx-bootstrap 4.0.1 Dependencies: "bootstrap": "3.3.7", "bootstrap-colorpicker": "2.5.1", "bootstrap-duallistbox": "3.0.6", "bootstrap-markdown": "2.10.0", "bootstrap-progressbar": "0.9.0", "bootstrap-slider": "9.8.0", "bootstrap-tags ...