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

storing audio files locally with Vue.js

Looking for a way to store a sound locally for my Battleship game rather than referencing it on the internet. Here's the code that triggers the sound: @click.prevent="fireSound('http://soundbible.com/grab.php?id=1794&type=mp3')" I atte ...

Manipulating nested arrays using index values in JavaScript

Can someone assist me in sorting a multidimensional array based on the value of the first index? I've tried using a for loop without success. Looking for solutions in JS or jQuery. I want to convert the following array: var pinData = [ ['< ...

Exploring NextJS with Typescript

Struggling to incorporate Typescript with NextJS has been a challenge, especially when it comes to destructured parameters in getInitialProps and defining the type of page functions. Take for example my _app.tsx: import { ThemeProvider } from 'styled ...

From Table to DIV: A Simple Conversion

I have encountered a major issue that has stumped me so far. Perhaps you can assist me. I am dealing with a table that appears as follows: __________________________________ | | time1 | time2 | time3 | +--------+-------+-------+-------+ | John | ...

Higher Order Component for JSX element - displaying JSX with wrapped component

I am looking to utilize a ReactJS HOC in order to implement a tooltip around JSX content. The function call should look similar to this: withTooltip(JSX, "very nice") To achieve this, I have created the following function: import React from "re ...

Issues arising with transferring information between components

My webpage had a header with a search engine input, a list of posts, and pagination all on one page. I made the decision to separate the header into its own component in a different Vue file. However, after making this change, searching for posts by their ...

Utilizing regular expressions to search through a .md file in JavaScript/TS and returning null

I am currently using fs in JavaScript to read through a changelog.MD file. Here is the code snippet: const readFile = async (fileName: string) => { return promisify(fs.readFile)(filePath, 'utf8'); } Now I am reading my .md file with this fu ...

Select the small image to reveal the larger overlay image

I have a grid of images and I want each image to expand into fullscreen when clicked. However, the JavaScript I am using is causing only the last image in the grid to overlay. How can I resolve this issue? Here is the code I am currently using: http://js ...

How to set and update the value of a TextField in ReactJS using useState and implement an onchange event handler for the input field in TypeScript

Just starting out with ReactJS and MUI development, I have a form with a MuiText field in TypeScript. Seeking assistance on how to use the useState method to update the text field value. Additionally, looking for guidance on adding an onchange function to ...

Searching for an individual MongoDB document using Express

I recently started working with MongoDB and express. I am trying to authenticate a user based on their username and password, but my code seems to always execute the "else statement" even when the correct credentials are entered. Below is the JavaScript f ...

Encountered an error stating 'Cannot read property 'user' of undefined' while attempting to generate a user document during account creation using Firebase

I'm having trouble adding the user ID to a new collection named 'accounts' during account creation. I keep encountering an error that says 'Cannot read property 'user' of undefined'. Can someone please help me troubleshoo ...

Is there a way to create a comprehensive list of all the possible winning combinations in a game of 4-Dimensional Connect Four?

Currently, I am developing a 4D Connect Four game using Javascript. The game can be accessed here. My next goal is to incorporate win-checking functionality. To simplify the process and save time, my plan is to pre-create a comprehensive list of all poten ...

The dynamic change of a required field property does not occur

I am facing an issue where one of my fields in the form should be mandatory or not based on a boolean variable. Even if the variable changes, the field always remains required. I'm puzzled about why my expressionProperties templateOptions.required is ...

When running the `mocha` command with `npm test`, no specific

Could use some help: I've encountered an issue while running a unit-testing command. The error messages are not being printed when there are errors, making debugging quite challenging. Here is the command I executed: and here's the package.json ...

Issue with accessing image files in assets folder with VueJs

I am struggling to showcase an image on my slider that is stored in the assets folder. Here is how my folder structure looks like: https://i.stack.imgur.com/8gduO.jpg This is what my code looks like: home.vue <img src="../images/firstslide.png"/> ...

Angular: Issue with click() event not functioning properly once dynamic HTML is rendered

There are a few HTML elements being loaded from the server side, and an Angular click() event is also included. However, the event is not firing after the elements are rendered. It is understood that the DOM needs to be notified, but this cannot be done. ...

Exclude certain packages from being processed in webpack

After setting up my webpack configuration, everything was running smoothly with the specified packages in the package.json: { "peerDependencies": { "react": "16.13.1", "react-dom": "16.13.1", ...

Creating a Chrome extension that opens multiple tabs using JavaScript

Currently, I am working on a chrome extension that includes several buttons to open different tabs. However, there seems to be an issue where clicking the Seqta button opens the tab three times and clicking the maths book button opens the tab twice. Below, ...

Can anyone help me with fixing the error message 'Cannot assign to read-only property 'exports' of the object' in React?

Recently, I decided to delve into the world of React and started building a simple app from scratch. However, I have run into an issue that is throwing the following error: Uncaught TypeError: Cannot assign to read-only property 'exports' of o ...

Conditional ngOptions in AngularJS allows you to dynamically update the options

Currently, I am working with a select box that iterates through an array of departments to identify eligible parent departments. <select class="editSelectBox" ng-model="dept.parentDepartment" ng-options="dept as dept.name for dept in depts track by de ...