Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

javascript - Vue.js add filename dynamically in a v-for loop

I have a component that dynamically adds inputs to my application. One input is a text input and another is a file input. In the case of text input everything works, I take the value via v-model. In the case of file input it is not possible to use v-model, instead v-on: change is used. How do I add the filename to the lists object dynamically?

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>

I'm using Vue 3.

Thanks in advance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can iterate with the index as well, then pass the index to the upload function, like this:

<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...