Steps for building a progressive v-file-input component in Vuetify

I am utilizing a v-file-input to manage certain documents. However, whenever a user attempts to add additional files by selecting them, it ends up wiping out the previous files. Ideally, I would like the v-file-input to be able to accumulate files and only allow clearing of values through the clearable icon.

                  <v-file-input
                    v-model="supportingDocumentsModel"
                    :show-size="1000"
                    color="primary"
                    label="Rate Supporting Documents"
                    placeholder="Select your supporting documents"
                    prepend-inner-icon="mdi-file"
                    prepend-icon=""
                    variant="outlined"
                    counter
                    comfortable
                    multiple
                    clearable
                  >
                    <template v-slot:selection="{ fileNames }">
                      <template v-for="(fileName) in fileNames" :key="fileName">
                        <v-chip
                          class="me-2"
                          color="blue-accent-4"
                          size="small"
                          label
                        >
                          {{ fileName }}
                        </v-chip>
                      </template>
                    </template>
                  </v-file-input>

In an attempt to enhance Yoduh's answer and make it more dynamic:

const updateFiles = (files : File[], persistentFiles : File[]) => {
    // Calculate new files by comparing persisted files with latest file selection
    const newFiles = files.filter(file1 => {
      return !persistentFiles.some(file2 => {
        return file1.name === file2.name
      })
    })
    // Set new files to persist
    persistentFiles.push(...newFiles)
    // Update v-model
    files = persistentFiles
}

function clearFiles(files : File[], persistentFiles : File[]) {
  persistentFiles = []
  files = []
}

Encountering issues while trying to pass models and persistent models as parameters.

Answer №1

To keep the v-model updated with the latest file selection, you must manually monitor and track the previous items so you can always re-add them to the v-model when it changes.

<v-file-input
  multiple
  v-model="files"
  clearable
  @update:model-value="updateFiles"
  @click:clear="clearFiles"
/>
const files = ref([])
const persistentFiles = ref([])

function updateFiles() {
  const newFiles = files.value.filter(file1 => {
    return !persistentFiles.value.some(file2 => {
      return file1.name === file2.name
    })
  })

  persistentFiles.value.push(...newFiles)
  files.value = persistentFiles.value
}

function clearFiles() {
  persistentFiles.value = []
  files.value = []
}

Vuetify Playground example

Edit:

If you have a dynamic number of v-file-inputs, consider defining files and persistentFiles as arrays of arrays. Each v-file-input can access its own array using an index.

Vuetify Playground multiple v-file-inputs example

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

How can it be that "Function" actually functions as a function?

In JavaScript, there exists a function called "Function". When you create an instance of this function, it returns another function: var myfunc = new Function('arg1','arg2','return arg1+arg2'); In the above example, the vari ...

Can we add to the input field that is currently in focus?

Recently, I've been working on a bookmarklet project. My goal is to append an element to the currently focused input field. For instance, if a user clicks on a textarea and then activates my bookmarklet, I want to insert the text "Hello" into that sp ...

Using Javascript and JQuery to create an alert that pops up upon loading the page is not effective

I am having trouble making an alert show up when my website loads. The Javascript code is functional when directly included in the HTML, but once I move it to a separate file named script.js and link it, nothing happens. Can someone please help me identify ...

Appending to an array or object in Node.js

Struggling to update an object in Node: exports.getAthleteData = function(accessToken, athleteId) { var athleteData = {}; strava.athlete.get({'access_token': accessToken},function(err, payload) { athleteData.push({ at ...

Is it possible to create a table using a loop in an SQLite query?

Welcome In the company where I work, Excel is currently being used to manage a large database of items for cost estimation purposes. To simplify this process, I am developing an Electron App that will replace Excel with a more user-friendly interface and ...

Changing the style of opening curly braces in JavaScript code styling

I have a piece of JavaScript code written for Vue that I would like to discuss. It is common practice in the JavaScript world to place the opening curly brace at the end of a line of code. <script> export default { name: 'newUser', data ...

Convert a prototype code to jQuery using AJAX syntax

Seeking advice on my code syntax as I transition from Prototype to jQuery. I currently have both frameworks running simultaneously and aim to streamline all scripts into jQuery for improved page load efficiency and speed. Migrating from Prototype to jQue ...

NodeJS Exporting Features

A situation is in front of me: var express = require('express'); var router = express.Router(); var articles = require('../model/articles.js'); router.get('/all', function(req, res, next) { res.json(articles.getAll()); ...

A coding algorithm for determining text similarity percentage by calculating the edit distance

I have a good understanding of various edit-distance algorithms in JavaScript, but my goal is to calculate text similarity as a percentage based on them. Can anyone provide guidance on how to implement this feature? ...

Conceal a TextBox by selecting a checkbox server control in ASP.NET/C# with the assistance of Jquery or Javascript

I've been attempting to dynamically hide and show a Textbox based on the state of a Checkbox. Here is the relevant source code: <asp:CheckBox ID="ShortStoryCheckBox" runat="server" /> <asp:TextBox ID="LeadTextBox" runat="server" Height="7 ...

Answer processing for the reminder dialog is underway

When I send a proactive message to a user, I want to initiate a 'reminder dialog'. The dialog is displayed, but when processing the response it goes back to the main dialog. This is how I currently set up my bot: const conversationState = new C ...

Function for swapping out the alert message

I am searching for a way to create my own custom alert without interfering with the rendering or state of components that are currently using the default window.alert(). Currently working with React 15.x. function injectDialogComponent(message: string){ ...

Is there a way to display a secondary header once the page is scrolled down 60 pixels?

.nav-header2{ background: purple; display: flex; justify-content: center; align-items: center; } .header2-container{ width: 68vw; height: 60px; padding: 0 2vh; border: 1px solid red; ...

Is there a way to efficiently parse and categorize erroneous JSON data in JavaScript?

Resolved my issue var allKeys = ["key","en","ar"]; for(var i=0;i<allKeys.length;i++) { for(j=0;j<jsonText.Sheet1.length;j++) { console.log(allKeys[i] + ' - ' + jsonText.Sheet1[j][allKeys[i]]); } } Live demonstration Appreciation ...

Unable to trap error using try-catch block within an asynchronous function

I'm attempting to integrate a try-catch block into an async function, but I am having trouble catching errors with status code 400 using the code below. const run = async () => { const response = await client.lists.addListMember(listId, { ema ...

Issue with jQuery incorrectly calculating height post-refresh

I am currently utilizing jQuery to vertically center various elements on a webpage. Due to lack of support in older versions of IE, I cannot use the table-cell CSS statement. Therefore, I am using jQuery to calculate half of the height and then position it ...

Node development does not operate continuously

I'm facing a minor issue with node-dev. I followed the instructions in the readme file and successfully installed it. However, when I run the command like so: node-dev somescript.js, it only runs once as if I used regular node without -dev. It doesn&a ...

Enhance parent style when child's data-state or aria-checked attributes are updated in React using Styled Components

Within a label, there is a button embedded as shown below: <MyLabel htmlFor='xx' onClick={() => onChange}> <MyButton id='xx' {...rest} /> Check it! </MyLabel> In the Developer Tools Elements section, the st ...

Utilizing Modifier Keys in jQuery for Form Submission

Imagine having a form structured like this: [ Animal name input field ] Add button Currently, when a name is entered and the enter key is pressed, a new animal with that name is added to a table. Now, I want to introduce a new feature called "slow add" ...

What is the best way to display an entire string in a DataGridPro cell without truncating it with an ellipsis?

After reviewing all of the available DataGrid documentation, I am still unable to find a solution for displaying strings in multiple lines within a cell without ellipses. The current behavior is as follows: https://i.stack.imgur.com/TO8vB.png What I am a ...