Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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?

share|improve this question
    
By security reasons you can't programatically set the value of a input type='file' tag. It is not a Vue issue. – Yerko Palma Jan 14 at 15:29
up vote 2 down vote accepted

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;
    }
  }
})
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.