Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically upload image in vue.js?

See the code: codepen

I want to post the data by form;

There is a add-image button,When I click the button first time and select the image,then show the image info in the page. When I click the button again,then show the two images info in the page.

The problem is: I can't set file value to the <input type='file' />

How to do this?

like image 537
Song Yongtao Avatar asked Sep 17 '25 11:09

Song Yongtao


1 Answers

Here's a potential solution forked from your original codepen.

I updated the viewmodel to contain an array of files. The v-for renders that array and includes a hidden file input for each item (same as in your code). However, unlike your sample, the file input is not model-bound to the file info. Instead, it calls the upload() method whenever its value is changed. The upload() method handles updating the underlying file info. With that in place, all the Add Image link needs to do is push a new object onto the files array and then trigger the click event on that file's input element (after it gets rendered).

Relevant code below.

Html

<ul>
  <li v-for="file in files">
    <div class="file_item">
      <div class="info">
        <strong>{{file.name}}</strong>
        <p>{{file.size | kb}}</p>
      </div>
    </div>
    <input id="file-{{$index}}" type="file" accept="image/*" @change="upload(file, $event)" style="display:none">
  </li>
</ul>
<div class="value_btn">
  <a href="#" v-on:click="addImage" class="add">
    <span>Add Image</span>
  </a>
</div>

Javascript

var vm = new Vue({
  el: "#item",
  data: {
    files : []       
  },
  methods: {
    addImage: function(){
      this.files.push({ name: "", size: 0})
        this.$nextTick(function () {
            var inputId = "file-" + (this.files.length-1);
            document.getElementById(inputId).click();
        });  
    },
    upload: function(file, e){
      var f = e.target.files[0];
      file.name = f.name;
      file.size = f.size;
    }
  }
})
like image 109
Peter Avatar answered Sep 20 '25 01:09

Peter