【问题标题】:Vue - File input element's @change not triggered when its files are set using ref - drag and drop file uploadVue - 使用 ref 设置文件时未触发文件输入元素的 @change - 拖放文件上传
【发布时间】:2021-10-20 03:02:23
【问题描述】:

我有一个用于拖放图像上传的文件输入。

    <input
          type="file"
          ref="FileInput"
          style="display: none;"
          @change="onFileSelect"
          accept=".jpg,.jpeg,.png,.tiff,.webp"
        />

在更改时触发 OnFileSelect 函数。

onFileSelect(e) {
      console.log("came here");
      const file = e.target.files[0];
      ...
      ...
      // here the code sends the files to be uploaded in server
}

有一个包含输入字段的放置区:

<div
      ref="dropZone"
      @drop="onDrop($event)"
      @click="$refs.FileInput.click()"
    >

而onDrop函数如下:

onDrop(e) {
      this.$refs.FileInput.files = e.dataTransfer.files;
      //this changes fileList in input but the onChange in input field is not triggered
      console.log("Yes", this.$refs.FileInput.files);
    },

当我在 dropzone 中放置图像文件并且输入中的 Filelist 也发生更改时触发 onDrop,但在 onDrop 函数之后不会调用函数 onFileSelect(应在输入更改时触发)。我怎样才能做到这一点?提前致谢!

【问题讨论】:

    标签: javascript html vue.js file-upload drag-and-drop


    【解决方案1】:

    onChange 输入类型文件的事件不会在dropEnd 上触发。

    相反,您必须修改当前的onChange 方法。这样你就可以使用相同的代码作为 drop end。

    像这样更新您的 onFileSelect 方法:

    onFileSelect(e) {
          console.log("came here");
          const file = e.target.files[0];
    
          uploadFile(file) // this method will be responsible for uploading file to server. Move all code written in onFileSelect to this method.
    }
    

    现在在 DropEnd 上,用文件参数简单地调用这个方法。

    onDrop(e) {
         uploadFile(e.dataTransfer.files[0])
        },
    

    【讨论】:

    • 感谢您的帮助。
    • 对为什么没有触发更改事件有任何解释吗?
    • 因为我们没有触发任何文件事件。拖放事件完全不同,与文件事件无关。
    猜你喜欢
    • 1970-01-01
    • 2021-02-05
    • 2013-11-20
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 2011-08-28
    相关资源
    最近更新 更多