【问题标题】:VueJs2:remove item from parent array in componentVueJs2:从组件中的父数组中删除项目
【发布时间】:2018-03-03 07:12:23
【问题描述】:

我有一个带有道具列表的组件。 List 是输入文件的列表。立即输入更改,我添加另一个输入。 如果我尝试删除,就会出现奇怪的行为。

https://jsfiddle.net/apokjqxx/115/

 removeAnother: function(item) {
  var vm = this;
  var num = vm.$parent.cornerList.indexOf(item);
  vm.$parent.cornerList.splice(num, 1);
},

如何重现:

  • 在第一个输入中选择文件
  • 在第二个输入中选择文件(将在第 1 步之后添加)
  • 在第三个输入中选择文件(将在第 2 步之后添加)
  • 然后单击以删除列表中的第一项

预期:删除了第一个项目,但删除了最后添加的项目

【问题讨论】:

    标签: arrays vue.js vuejs2


    【解决方案1】:

    Use a key 在你的名单上。

    <div v-for="(item, index) in list" :key="item.id">
    

    我修改了你的小提琴,为添加到 cornerList 数组的每个对象生成一个 id

    var formuploadimage = Vue.extend({
      template: '#template-form-upload-image',
      props: {
        list: {
          type: Array
        }
      },
      data: function() {
        return {
          isFileChanged: false
        }
      },
      watch: {
        validCnt: function() {
           
        },
      },
    
      methods: {
        onFileChange: function(item) {
    	 var vm = this; 
          let id = Math.max.apply(Math, vm.$parent.cornerList.map(c => c.id)) + 1
            var newItem = {id};
            vm.$parent.cornerList.push(newItem);
        },
        removeAnother: function(item) {
          var vm = this;
          var num = vm.$parent.cornerList.indexOf(item);
          vm.$parent.cornerList.splice(num, 1);
        },
      },
    });
    
    
    
    
    var app = new Vue({
      el: ".lists-wrappers",
      data: {
        cornerList: [{id: 1}],
      },
      components: {
    
        formuploadimage: formuploadimage
      },
      methods: {
    
      },
    
    });
    .select-file{
      width:250px;
      border:1px solid red;
    }
    <script src="https://unpkg.com/vue@2.4.4/dist/vue.js"></script>
    <div class="lists-wrappers">
      <formuploadimage :list="cornerList"></formuploadimage>
    </div>
    
    
    <script type="text/x-template" id="template-form-upload-image">
      <div>
    
        <div v-for="(item, index) in list" :key="item.id">
          
          <div class="select-file">
          <a href="#" v-on:click="removeAnother(item)">REMOVE</a><br/>
            <label for="file-input">
              +Add photo
            </label>
            <input type="file" @change="onFileChange(item)"  />
          </div>
        </div>
      </div>
    </script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 2014-09-21
      • 2021-10-19
      • 1970-01-01
      • 2013-06-08
      相关资源
      最近更新 更多