Dynamically Adding Filenames in Vue.js with v-for Iteration

I'm currently facing an issue with dynamically adding inputs to my Vue 3 application. Specifically, I have a component that adds both text and file inputs dynamically. While the text input works flawlessly using v-model, the file input requires me to use v-on:change instead. My question is, how can I dynamically add the filename to the lists object when dealing with file inputs?

Template

<template lang="html">

    <div v-for="list in lists">

        <input type="text" v-model="list.text" >
        
        <input type="file" @change="upload">

    </div>
    
    <button @click="addItem">Add Item</button>

</template>

Script

<script>

export default {

    data() {
        return {
        lists:[{text: '', filename: '',}]
        }
    },
    
    methods: {
        addItem() {
            this.lists.push({ text: '', filename: '' })
        },

        upload(event) {
            this.lists.filename = event.target.files[0].name
        },
    }
}

</script>

Any suggestions or insights on resolving this issue would be greatly appreciated!

Answer №1

Another way to iterate with the index is by passing it to the upload function directly:

<script>

export default {

    data() {
        return {
        lists:[{text: '', filename: '',}]
        }
    },
    
    methods: {
        addItem() {
            this.lists.push({ text: '', filename: '' })
        },

        upload(event, index) {
            this.lists[index].filename = event.target.files[0].name
        },
    }
}

</script>
<template lang="html">

    <div v-for="(list, index) in lists">

        <input type="text" v-model="list.text" >
        
        <input type="file" @change="upload($event, index)">

    </div>
    
    <button @click="addItem">Add Item</button>

</template>

Answer №2

To connect with the array index, there is no requirement for using the upload method.

new Vue({
      el: '#app',
      data() {
        return {
          title: "Vue app",
          lists:[{text: '', filename: '',}]
        };
      },
      methods:{
      addItem() {
            this.lists.push({ text: '', filename: '' })
        }
      }
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app"><h2>{{title}}</h2>
     <div v-for="(list,i) in lists">

        <input type="text" v-model="lists[i].text" >
        
        <input type="file" v-model="lists[i].filename">

    </div>
    
    <button @click="addItem">Add Item</button>
    <pre>{{lists}}</pre>
    </div>

Answer №3

Follow these steps:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<input id='inputfile' type='file' name='inputfile' onChange='getoutput()'>

new Vue({
    el: '#app',
    data() {
        return {
            title: "Vue app",
            lists:[{text: '', filename: '',}]
        };
    },
    methods:{
        addItem() {
            this.lists.push({ text: '', filename: '' })
        },
        getFile(filePath) {
            return filePath.substr(filePath.lastIndexOf('\\') + 1).split('.')[0];
        },
        getoutput(e, index) {
            let fileName = this.getFile(e.target.value);
            let fileExtention = e.target.value.split('.')[1];
            this.lists[index].filename = `${fileName}.${fileExtention}`;
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app"><h2>{{title}}</h2>
     <div v-for="(list,i) in lists">

        <input type="text" v-model="lists[i].text" >
        
        <input type="file" @change="getoutput($event, i)">

    </div>
    
    <button @click="addItem">Add Item</button>
    <pre>{{lists}}</pre>
    </div>

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

Tips for embedding a script into an HTML document

I've been experimenting with tinymce npm and following their guide, but I've hit a roadblock. Including this line of code in the <head> of your HTML page is crucial: <script src="/path/to/tinymce.min.js"></script>. So, I place ...

What is the best way to retrieve distinct id values from a form in Rails when sending a DELETE request via AJAX?

I am determined to grasp the intricacies of AJAX and how it operates, hence, I prefer not to use "remote: true" for this task. The issue at hand is that despite attempting to send a DELETE request to the server using a form input, each submission results i ...

Effortlessly retrieving the id attribute from an HTML tag using jQuery

Currently, I am encountering an issue with a code snippet that is designed to extract the value from an HTML tag. While it successfully retrieves a single word like 'desk', it fails when attempting to do so for an ID consisting of two or more wor ...

Retrieving Posts from Extensive JSON Data

I'm currently working on a project where I am coding a system to monitor updates on the Ontario Immigrant Nominee Program Updates page and then send out email alerts whenever a new article is posted. Initially, I implemented this in PHP but now I want ...

JavaScript is a powerful tool for reading JSON files

I'm trying to figure out how to parse a nested object in JSON using JavaScript. Here's the code I have so far: var myRequest = new Request('test.json'); fetch(myRequest) .then(function(response) { return response.json(); }) .then( ...

Utilizing Vue component data within inline CSS of a Vuetify component: a step-by-step guide

I am currently working on a list component that is dynamically generated from data and I have a specific requirement to style each item based on the color provided in the data. Here is an example of the Vue component: new Vue({ el: '#app', ...

Is there a vulnerability in the routing security of Angular/MEAN.io?

After setting up the MEAN stack (MongoDB, Express.js, AngularJS, Node.js) and launching the sample program from mean.io, I found a basic app where you can log in and create blog "articles" for testing purposes. To my surprise, when I removed the '#!& ...

Combining two JSON objects with sailsjs-nodejs to create a single merged object

Hello everyone, I am a beginner with Sailsjs-Nodejs. Currently, I have two JSON Objects in my controller that I need to merge/join in order to create a third object to send as a response. The output when using res.send(obj1) is: [ { total_fare: "37 ...

java code unicode feature in csharp

Here's the code I am using: $(document).ready(function () { var breadCrumps = $('.breadcrumb'); breadCrumps.find('span').text("<%= ArticleSectionData.title %>"); }); The 'title' property contains values en ...

What is the most efficient way to find the sum of duplicates in an array based on two different properties and then return the

var data = [ { "amount": 270, "xlabel": "25-31/10", "datestatus": "past", "color": "#E74C3C", "y": 270, "date": "2020-10-31T00:00:00Z", "entityId": 1, "entityName": "Lenovo HK", "bankName": "BNP Paribas Bank", "b ...

Prevent unchecking a checked list item by clicking on it

Is it possible to prevent the user from unchecking a list item once it has been checked? Your assistance is greatly appreciated! $(".collectioncontainer ul li").click(function(){ $('.collectioncontainer ul li.checked').not(this).removeClass( ...

Is it possible to use just one <map> tag for multiple images in jQuery or JavaScript?

I have multiple images on my website <img usemap="#slideMap_branches" src="branches.png" width="890" height="270" alt="Slide 4"> <img usemap="#slideMap_order" src="order.png" width="890" height="270" alt="Slide 2"> <img usemap="#slideMap_c ...

Trouble updating Vue 2 project using vue-cli due to npm update failure

I set up a Vue 2 project using vue-cli and attempted to execute npm update. Unfortunately, I encountered the following error: { npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-c ...

Using Vue for Firestore pagination

Utilizing the bootstrap-vue pagination component: <b-pagination v-model="currentPage" :total-rows="rows" :per-page="perPage" ></b-pagination> Component.vue: export default class PaginatedLinks extends Vue { public currentPage: number ...

Ensuring Compliance with GDPR through Cookie Consent Logic

Since the introduction of GDPR, I find myself in need of clarity on the steps to take both server-side and client-side to ensure compliance. Apologies for the plethora of questions. I currently have a first-party cookie that is used to store a session coo ...

Unresolved promise rejection on Repl.it

I decided to add a basic leaderboard feature to my game on Repl.it, so I set up a node.js backend for it. Here's the code snippet for the backend: const express = require('express'); const Client = require('@replit/database'); cons ...

JavaScript inquiry

How do you typically utilize JavaScript in your projects? I often use it for form validation, creating dropdown menus, and more. Do you have any unique ways of using JavaScript? Personally, I find jQuery to be a superior tool in certain situations... ...

The variable $t has not been defined within the filter component

I implemented a filter on my component: filters: { formatStatus (value) { let status = { active: { text: this.$t('general.successful'), class: 'secondary--text' }, processing: { text: this.$t('gener ...

What is the best way to retrieve a jobID from Kue?

I am currently working with Express and I'm facing a challenge in creating a job whenever someone posts to my route. My goal is to have the response include the job.id, but the job id is only generated within the callback of my queue.createFunction. I ...

Total of Vue Component Subtotals

One of the challenges I'm facing in my Vue app is calculating the total of subtotals. Every component has its own subtotal that depends on user input. I need to combine these individual subtotals and display the result in an input field outside of th ...