What is the best way to send data from methods to a function in Vue.js?

How can I pass a value from a method to another function in Vue.js?

I have a value in my method, but I need to pass this value to another function. How can I achieve this?

methods: {
  getDataSource() {
    let self = this;
    arr.forEach((item) => {
      //debugger;
      let tokens = item.path.replace(/^\/|\/$/g, "").split("/");
      let fid = item.fid;
      let current = tree;
      for (let i = 0; i < tokens.length; i++) {
        if (!current[tokens[i]]) {
          current[tokens[i]] = {
            fid: item.fid
          };
        }
        current = current[tokens[i]];
      }
      let ffid = Number(item.fid) + 1;
      //console.log(ffid);
    });
}


function uploadFileChunk(fileData, uploadInfo, destinationDirectory) {
  let self = this;
  //debugger
  let reader = new FileReader();
  reader.onload = function() {
    console.log(reader.result);
  }
  reader['readAsDataURL'](fileData);
  return objectProvider.uploadFileChunk(
    fileData,
    uploadInfo,
    destinationDirectory
  );
}

I want to pass the value of ffid to the function uploadFileChunk. How can I retrieve the ffid values?

Answer №1

Whenever both handlers are located in the same file, you have the ability to pass it through in the following manner:

methods: {
  getDataSource() {
    let self = this;
    arr.forEach((item) => {
      //debugger;
      let tokens = item.path.replace(/^\/|\/$/g, "").split("/");
      let fid = item.fid;
      let current = tree;
      for (let i = 0; i < tokens.length; i++) {
        if (!current[tokens[i]]) {
          current[tokens[i]] = {
            fid: item.fid
          };
        }
        current = current[tokens[i]];
      }
      let ffid = Number(item.fid) + 1;
      //As the function is defined externally, try calling it as shown below
      uploadFileChunk(ffid); // Remember that the upload file Chunk function requires three arguments to be passed, so ensure that you provide the other two as well
    });
}

Answer №2

Simply include the function as a method and utilize 'this'

methods: {
  getDataSource() {
    let self = this;
    arr.forEach((item) => {
      //debugger;
      let tokens = item.path.replace(/^\/|\/$/g, "").split("/");
      let fid = item.fid;
      let current = tree;
      for (let i = 0; i < tokens.length; i++) {
        if (!current[tokens[i]]) {
          current[tokens[i]] = {
            fid: item.fid
          };
        }
        current = current[tokens[i]];
      }
      let ffid = Number(item.fid) + 1;
      this.uploadFileChunk(ffid)      
    });

  uploadFileChunk(fileData, uploadInfo, destinationDirectory) {
    let self = this;
    //debugger
    let reader = new FileReader();
    reader.onload = function() {
      console.log(reader.result);
    }
    reader['readAsDataURL'](fileData);
    return objectProvider.uploadFileChunk(
      fileData,
      uploadInfo,
      destinationDirectory
    );
  }
}

if you truly wish to use it as an independent function, my suggestion would be to create a helper file and import it

upload-helpers.js (The name is at your discretion)

export function uploadFileChunk(fileData, uploadInfo, destinationDirectory) => {
    let self = this;
    //debugger
    let reader = new FileReader();
    reader.onload = function() {
      console.log(reader.result);
    }
    reader['readAsDataURL'](fileData);
    return objectProvider.uploadFileChunk(
      fileData,
      uploadInfo,
      destinationDirectory
    );
  }


In your Vue component

import { uploadFileChunk } from './upload-helpers'

methods: {
  getDataSource() {
    let self = this;
    arr.forEach((item) => {
      //debugger;
      let tokens = item.path.replace(/^\/|\/$/g, "").split("/");
      let fid = item.fid;
      let current = tree;
      for (let i = 0; i < tokens.length; i++) {
        if (!current[tokens[i]]) {
          current[tokens[i]] = {
            fid: item.fid
          };
        }
        current = current[tokens[i]];
      }
      let ffid = Number(item.fid) + 1;
      uploadFileChunk(ffid)  
    });
}


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

The error message "TypeError: Cannot read properties of undefined (reading 'prototype')" is encountered in Next.js 13 when trying to access the prototype of an

I tried to integrate the downshift library into my project. However, when I attempted to use a basic example from the GitHub repository here, I encountered an error. Current versions: Next.js: 13.2.4 React: 18.2.0 Upon further investigation, it seems lik ...

store user settings in local storage

After writing some code with a link that toggles text visibility upon click, I now want to incorporate saving this state in web storage so that it persists upon page reload. As a beginner in JavaScript and HTML, this task has proven challenging for me. Th ...

How to run JavaScript code in Robot Framework using Selenium2Library

I am currently conducting automated testing on a web application based on extjs using robotframework and selenium2library. However, I'm facing difficulty in locating certain elements within a table component. I have come across the Execute JavaScript ...

Deciphering JavaScript Arrays

Looking to extract the values of {r=1, g=4, b=6} from an array. Any suggestions on how to store each individual value (r, g, b) in its own variable? ...

Tips for altering the contents of a state in react by toggling items in and out

Here's a challenge I'm facing: I need to display products based on the checkboxes toggles. If none of the checkboxes are toggled, the product array should be empty. If the men's checkbox is toggled, only men-related products should be shown, ...

The HTML button with Google's material-icons appears noticeably small when displayed on mobile devices

Looking to design a basic HTML page with a button placed in the lower right corner? Check out the code below: <!DOCTYPE html> <html> <head> <title>Sample Page</title> <style> /* Styles for the container * ...

vue end-to-end testing using axios and making real server requests

Entering the realm of vue testing, I am embarking on creating an integration test for our Vue SPA using axios and mocha. I am keen to conduct some tests that involve actual api calls to our server without simulation, in order to verify if everything funct ...

The condition is not being recognized after clicking the third button

When the button is clicked for the first time in the code snippet below, all divs except for the red one should fade out. With each subsequent click, the opacity of the next div with a higher stack order should be set to 1. Everything works fine until the ...

Tips for setting up Angular $resourceProvider to use the GET method

I am currently utilizing $resource within AngularJS. I am looking to set up $resource using $resourceProvider in a way that allows me to manage the server response. For instance When making a get request for a user profile, I want to handle specific erro ...

Rearrange AxisX and AxisY in Lightningchart library

I am currently utilizing the lightningchart library and intend to create a ChartXY with an AreaSeries attached to it. To achieve this, I have written the following code using React and TypeScript: import { useEffect, useRef } from 'react'; impor ...

Tips for managing onClick code when a user selects "open link in new tab" within a React js environment

How can I ensure that my tracking code runs when a user clicks a button in my React project, even if they open it in a new tab? Is there a solution for this in React JS? Here's a simple example: var Hello = React.createClass({ render: function( ...

Issues with the functionality of the sliding menu in Angular are being encountered when trying to use $

Challenge I am facing an issue with a slider menu feature that I integrated into a mobile application for navigation purposes. The menu is functioning properly - it displays, allows flicking of the initial links, and can be closed by pushing the backdrop. ...

Working on the image for presentation

I am looking to determine the size of an image and then display it as a cropped version with a set width and height. What is the best way for me to accomplish this task? Here's the code that I have attempted: var filesSelected = document.getElemen ...

What could be causing the JSON output to appear in a disordered fashion?

I am attempting to retrieve weather information for 8 different locations. Utilizing a weather API that requires longitude and latitude, it returns JSON output with the weather data for each location. I provided the coordinates in sequential order from 0 t ...

Unable to close Bootstrap 5 modal

All of my modal forms are functioning properly, except for one that I migrated from Bootstrap 4 to Bootstrap 5. This particular modal refuses to close. Neither the Close button (the X at the top of the popup) nor the Cancel button will close the modal. I ...

Parallel mapping with simultaneous multiple inserts

I am working on inserting a list of topics with unique slugs into a MongoDB database. Here are two example topics: { title: "my title" }, { title: "my title" } After generating the slugs, I need to insert the topics: // Insert each topic async.map( ...

Troubleshooting Vue.js 2: Difficulty with Vue locating files stored in the /assets directory (v-for loop)

My Vue-cli 3 project with Webpack has the following folder structure: /public /src /assets p1.jpg p2.jpg App.vue main.js I have read that in order for Webpack to recognize the /assets directory, require() should be used in JavaScript files ...

The Datalist feature in HTML5 offers an auto-suggest functionality that displays a list of options beginning with the

In my project, I am utilizing HTML5 Datalist for autosuggestion. By default, HTML5 follows the keyword contains approach rather than the starts with approach. For example, if my datalist includes one, two, three and I type "o" in the search box, it displ ...

Top method for concealing image within adaptable block

I am currently working on making the header slideshow responsive. I encountered an issue where I couldn't use the CSS property background with cover. Instead, I need to utilize <img> inside a div. <div class="parent"> <img src="slide ...

There seems to be an issue with the createFiberrFromTypeAndProps function

import React from 'react'; import { MDBContainer, MDBCarousel, MDBCarouselInner, MDBCarouselItem, MDBTestimonial, MDBAvatar, MDBIcon } from 'mdbreact'; const TestimonialsPage = () => { return ( < ...