首页 > 解决方案 > 如何从 Vue.js 中的方法向函数传递值?

问题描述

如何从 Vue.js 中的方法向函数传递值?

我在方法中得到了一个值,但我需要将此值传递给其他函数,我该怎么做?

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
  );
}

我想将 ffid 值传递给函数 uploadFileChunk,如何获得 ffid 值?

标签: javascriptfunctionvue.jsvuejs2

解决方案


只需将函数添加为方法并使用它

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
    );
  }
}

如果您真的想将其用作独立功能,我建议您创建一个帮助文件并导入它

upload-helpers.js(名称由您决定)

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
    );
  }


在你的组件 Vue

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)  
    });
}



推荐阅读