When multiple instances of a Vue Filepond component are used on the same page, the input event emitter is saving the data in the v-model of the last

A new file-uploader component has been developed with the following setup:

<template>
  <div>
    <file-pond
      :id="id"
      :key="id"
      name="files"
      ref="pond"
      v-bind="$attrs"
      v-on:activatefile="onActivateFileClick"
      v-on:removefile="onRemoveFileClick"
      v-bind:files="files"
    />
  </div>
</template>

<script>
import { lookup } from "mime-types";

// Include FilePond
import vueFilePond, { setOptions, addFile } from "vue-filepond";

// Include plugins
import FilePondPluginFileValidateType from "filepond-plugin-file-validate-type/dist/filepond-plugin-file-validate-type.esm.js";
import FilePondPluginImagePreview from "filepond-plugin-image-preview/dist/filepond-plugin-image-preview.esm.js";

// Include styles
import "filepond/dist/filepond.min.css";
import "filepond-plugin-image-preview/dist/filepond-plugin-image-preview.min.css";

// Create the FilePond component
const FilePond = vueFilePond(
  FilePondPluginFileValidateType,
  FilePondPluginImagePreview
);
const FILE_UPLOAD_SERVER_URL = "http://localhost:8181";

export default {
  name: "file-uploader",
  components: {
    FilePond
  },
  props: {
    id: {
      type: String,
      required: true
    },
    value: {
      default: [],
      required: true
    }
  },
  mounted() {
    this.files = this.value.map(file => ({
      source: file.filePath,
      options: {
        type: "local",
        file: {
          name: file.originalFileName,
          size: file.fileSize,
          type: lookup(file.originalFileName)
        }
      }
    }));
    ...
  },
  data: function() {
    return {
      files: []
    };
  },
  computed: {},
  methods: {
    onRemoveFileClick: function(error, file) {
      ...
    },
    onActivateFileClick: function(file) {
      ...
    }
  }
};
</script>

The above component is implemented in the application using the code snippets below:

<file-uploader
  id="fileuploader"
  key="fileuploader"
  v-model="files"
  required="true"
  allow-multiple="true"
  accepted-file-types="application/pdf"
 />
<file-uploader
  id="fileuploader1"
  key="fileuploader1"
  v-model="files1"
  required="true"
  allow-multiple="true"
  accepted-file-types="application/pdf"
 />

During the file upload process of the first component, an input event is emitted. However, the emitted value is being stored in the v-model of the last component (in this case files1) instead of the respective v-model.

Answer №1

To have different identifiers, you can incorporate the "addFile" event within the FilePond element.

FilePond Component :

<FilePond
  :id="id"
  name="files"
  ref="pond"
  v-bind="$attrs"
  v-on:activatefile="onActivateFileClick"
  v-on:removefile="onRemoveFileClick"
  v-on:addfile="setOptionsOnAddFile"
/>

setOptionsOnAddFile Method :

setOptionsOnAddFile() {
  setOptions({
    server: {
      url: FILE_UPLOAD_SERVER_URL,
      process: {
        url:
          process.env.api.file.uploadFile +
          "?folderName=" +
          this.id +
          "&&id=" +
          this.$store.state.fileId,
        method: "POST",
        headers: {
          Authorization: "Bearer " + cookies.get("x-access-token"),
        },
        onerror: (response) => response.data,
        onload: (response) => {
          response = JSON.parse(response);
          //  this emit is storing value into last component`s v-model in a page.
          this.$store.commit("SET_FILES", response.data.filesUploaded);
          this.$emit("input", [
            // ...this.value,
            ...response.data.filesUploaded,
          ]);
          this.$store.commit("SET_FILE_ID", "");
          return response.data.filesUploaded[0];
        },
      },
    },
  });
},

Therefore, it is possible to utilize multiple file-pond components on the same page with distinct identifiers for uploading files.

Answer №2

To resolve this issue, it is important to remember that you should execute the setOptions function on each specific file-pond instance rather than globally.

One approach to tackle this problem is as follows:

// Add this code snippet to your template
<file-pond
    ref="pond"
    @init="init"
    ....
/>

// Include this in your script
const pond = ref(null);

function init() {
    pond.value.addFile(/* path to your file */);

    pond.value._pond.setOptions({
        ...
    });
}

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

Determine if a JSON object is void

Using jQuery, I am checking whether the object returned from an AJAX call is empty or not. In the first example, the AJAX call is successful and returns some data. console.log("obj before JSON parse:", response); var test = $.isEmptyObject(response); con ...

Animations in Phaser do not function properly on touch screen devices, although they work seamlessly on desktop computers

In my phaser.js game, I have a variety of animations set up: this.anims.create({ key: 'catchingUp', frames: this.anims.generateFrameNumbers('android', { start: 0, end: 4}), frameRate: this.frameSpeed * 6, ...

Use the lodash chunk method to split a mapped array into two separate arrays

Looking to organize some data into tables? I have a dataset from an API that you might find helpful. [ { date: "1/11", data: [ { camera: "camera 1", count: 10 }, { camera: "camera 2", count: 20 ...

Tips for adjusting the <object> video to perfectly match the width and height of its parent container

<div id="player" width='2000px' height='600px'> <object id="pl" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"> <param name='url' value='Video/3.mp4'/> <param name='ShowContro ...

Error: Incorrect Path for Dynamic Import

Recently, I've been trying to dynamically load locale files based on the locale code provided by Next.js. Unfortunately, every time I attempt a dynamic import, an error surfaces and it seems like the import path is incorrect: Unable to load translatio ...

Is there a way to retrieve the quantity of children from an element using protractor?

I am currently working with Protractor and I need to determine the amount of child components associated with a specific element. The element in question belongs to a table category. let table = element(by.css('#myTable')); My objective now is ...

Retrieve data from a local JSON file and showcase it in a list within a Next.js project. The error "Property 'data' does not exist on type String

Having trouble displaying the names of crates (which are filled with records/albums) from a local JSON file. The names aren't showing up and I'm wondering if I should be using params or if perhaps not stringifying the JSON would help. Visual Stud ...

What is the best way to retrieve the data from this date object?

How can I access the date and time in the code below? I've attempted using functions within the Text block without success. It's unclear to me what mistake I'm making or how to correctly access this object, or transform it into an object th ...

Determine whether a WebElement contains a particular content within the :after pseudo class

After locating my element in Selenium, I've come across an interesting challenge. IWebElement icon = box.FindElement(By.ClassName("box-icon")); Sometimes, this element (icon) has a content set as follows: &:after { content: $icon-specia ...

Encountering the error message "Error: Unable to process rejection (TypeError): that.setState function is not defined" while using ReactJS

I've been working on a dynamic chart that changes based on the Slider value. I did some research and everyone suggests that I need to bind it to resolve this error. However, no matter how many times I try to bind the function in different ways, I keep ...

Utilizing Element IDs for JQuery Tab Implementation

Having two buttons and two divs with paragraphs, I want to create tabs without adding new classes or IDs. Can I achieve tab switching using the existing IDs that end with "_one"? For instance: The first button has the ID "tab_button_one" and the first di ...

launch hyperlink in bootstrap popup

I have a challenge with showcasing multiple videos in a single modal without creating separate modals for each button. The function I found was effective with an older version of Bootstrap, but it no longer works with Bootstrap 3.3.7. Below is the HTML co ...

The show-word-limit feature is malfunctioning on the element.eleme.io platform

After attempting to utilize the show-word-limit attribute of the input element, unfortunately the character count did not display. Below is the code snippet that was used: <el-input type="textarea" placeholder="Please input" ...

Angular2 - Access to fetch at 'https://example.com' from

Requesting some guidance on integrating the forecast API into my angular2 application. Currently facing a Cross-Origin Error while attempting to access the API. Any suggestions on resolving this issue? search(latitude: any, longitude: any){ consol ...

Is there a way to automatically highlight an input field upon page load?

Is there a way for certain websites to automatically highlight an input field upon entering a page? For instance, YouTube's login page automatically highlights the Username field as soon as you land on it. Even this site, particularly on the Ask Ques ...

How should I position <script> tags when transferring PHP variables to JavaScript?

I've attempted to find an answer without success due to its specificity. Within the header.php file, which serves as the header of the website, various scripts are included to enable jQuery functionality. Additionally, there is a file called workscri ...

React final form does not support custom input values

Below is the code in question: ... return ( <FormItem key={name}> <Label htmlFor={id}>{camelCaseToTitleCase(fieldKey)}</Label> { fieldKey === 'homePhone' ? ...

Run JavaScript code to retrieve the console log using Selenium WebDriver or WatiN

(Apologies for the detailed explanation) I am looking to ensure a page loads entirely before proceeding, but it seems browsers have varied responses when attempting to use readyState or onLoad. In the application I am currently developing, a specific l ...

Remove class using jQuery when clicked for the second time and also disable hover effect on the second click

I'm trying to implement a feature that removes the 'active' class when a checkbox is clicked for the second time, similar to how Pinterest handles checkboxes for Twitter and Facebook. Here's what I have tried so far: $(".add_link_twitt ...

An issue occurred while trying to run the 'npm run serve' command following the installation of V

For more information, visit: https://vuetifyjs.com/en/getting-started/quick-start Initially, I executed the command vue create my-app followed by npm run serve and it ran smoothly without any errors. However, upon attempting to add Vuetify using the comm ...