splice not working with a array row vue js

狂风中的少年 提交于 2020-12-26 05:14:56

问题


I have a Object array but when i want remove a object from array list only items are deleted from the end

<div class="hours" v-for="(time, index) in hour" :key="index">

then I put the click function on an icon

<b-icon
v-if="time.delete"
icon="x"
width="20"
height="20"
class="delete-time"
@click="deleteTime(index)"
></b-icon>

but when I go to do the delete

methods: {
moment, 
deleteTime(index) {
       this.hour.splice(index, 1);
 },

回答1:


I discovered that the challenge is that you need to add a unique id in HOUR, as you had earlier. I have updated my previous answer

 hour: [
            {
              id: 1,
              "item-1": 10,
            },
            {
              id: 2,
              "item-2": 11,
            },
            {
              id: 3,
              "item-3": 12,
            },
          ],

Take note that key is assigned to the unique id gotten from the hour object.

:key="time.id"

And deleteItems takes index has a parameter

@click="deleteTime(index)"
      <div class="hours" v-for="(time, index) in hour" :key="time.id">
        <button @click="deleteTime(index)">
          Content {{time.id}}
        </button>
      </div>

Then your method goes

deleteTime(index) {
            this.hour.splice(index, 1);
          },



回答2:


Try this

deleteTime(index) {
       this.hour.splice(index, 1);
 },



回答3:


this should work, always add an id for tracking, btw if you used splice here it will work also

new Vue({
  el: '#app',
  data: {
    hour: [
      { id: 1, name: "one" },
      { id: 2, name: "two" },
      { id: 3, name: "three" }
    ]
  },
  methods: {
    deleteTime(id) {
      this.hour = this.hour.filter(item => item.id != id);
    }
  },
});
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>

<div id ="app">
  <div class="hours" v-for="(time, index) in hour" :key="index">
    {{ time.name }}
    <button @click="deleteTime(time.id)">del</button>
  </div>
</div>


来源:https://stackoverflow.com/questions/64927581/splice-not-working-with-a-array-row-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!