VueJS - 输入文件转发器

时间:2017-12-25 10:04:10

标签: javascript vue.js

我想从数组中删除项目,但是有相同的项目,js删除最后一项! enter image description here

let app = new Vue({
  el: '#app',
  data: {
    items: []
  },
  methods: {
    addItem() {
      this.items.push('');
    },
    removeItem(index) {
      this.items.splice(index, 1);
    }
  }
});
<script src="https://unpkg.com/vue@2.1.10/dist/vue.js"></script>
<div id="app">
  <ul class="list-group">
    <li class="list-group-item" v-for="(item , index) in items">
      <a href="#" v-on:click.prevent="removeItem(index)">remove</a>
      <input name="form[]" type='file'>
    </li>
  </ul>
  <button @click='addItem'>new item</button>
</div>

JSFiddle:https://jsfiddle.net/6hvbqju2/

2 个答案:

答案 0 :(得分:2)

Vue在处理元素列表时使用“就地补丁策略”。当依赖表单输入值时,此策略不适用。

使用v-for指令时,最好定义一个v-bind:key,以便为Vue提供跟踪每个节点的提示。

我们会在items数组中存储数字并将其用作关键字。在您的情况下,您应该使用可以作为唯一键的项目属性。

let app = new Vue({
  el: '#app',
  data: {
    counter: 0,
    items: []
  },
  methods: {
    addItem() {
      this.items.push(this.counter++);
    },
    removeItem(index) {
      this.items.splice(index, 1);
    }
  }
});
<script src="https://unpkg.com/vue@2.1.10/dist/vue.js"></script>
<div id="app">

  <ul class="list-group">
    <li class="list-group-item" v-for="(item , index) in items" :key="item">
      <a href="#" v-on:click.prevent="removeItem(index)">remove</a>
      <input name="form[]" type='file'>

    </li>
  </ul>
  <button @click='addItem'>new item</button>


</div>

答案 1 :(得分:1)

您的代码工作正常,但是, 这是因为文件输入自动完成行为

参见此示例

&#13;
&#13;
let app = new Vue({
  el : '#app',
  data : {
    items: [],
  },
  methods : {
    addItem() {
      this.items.push({file: null});
      console.log(this.items)
    },
    removeItem(index) {
      this.items.splice(index,1);
    },
    handleChange(item, event){
      item.file = event.target.files["0"];
    }
  }
});
&#13;
.upload-btn-wrapper {
  position: relative;
  overflow: hidden;
  display: inline-block;
  vertical-align: middle;
}
.btn {
  border: 1px solid gray;
  color: gray;
  background-color: white;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 15px;
  font-weight: bold;
}
.upload-btn-wrapper input[type=file] {
  font-size: 100px;
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
}
&#13;
<script src="https://unpkg.com/vue@2.1.10/dist/vue.js"></script>

<div id="app">
  <ul class="list-group">
    <li class="list-group-item" v-for="(item , index) in items">
      <a href="#" v-on:click.prevent="removeItem(index)">remove</a>
      <div type="button" class="upload-btn-wrapper">
        <button class="btn">{{ item.file ? item.file.name : 'Choose File' }}</button>
        <input name="form[]" type="file" @change="handleChange(item, $event)">
      </div>
    </li>
  </ul>
  <button @click='addItem'>new item</button>
</div>
&#13;
&#13;
&#13;