列表项从下到上删除,但不是从上到下

问题描述 投票:0回答:1

我列出了链接上的项目列表。在每个元素附近有一个按钮,当点击该按钮时,该元素应该从网站和api中删除。事实是,当我点击删除按钮时,api和网站上的所有内容都是正常的,如果从下往上删除元素,这是正常的,如果从上到下,则无法正常工作。我知道问题在于拼接参数,但我不知道如何修复它。

Screenshot of list

<template>
  <div id="app">
    <ul>
      <li v-for="(post, id) of posts">
        <p>{{ post.title }}</p>
        <p>{{ post.body }}</p>
        <button  @click="deleteData(post.id)">Delete</button>
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'app',
  data () {
    return{
      posts: [],
    }
  },

    created(){
      axios.get('http://jsonplaceholder.typicode.com/posts').then(response => {
        this.posts = response.data
      })
    },
    methods: {
        deleteData(id) {
          axios.delete('http://jsonplaceholder.typicode.com/posts/' + id)
                    .then(response => {
                      console.log('delete')
                        this.posts.splice(id-1, 1)
                      })
                    .catch(function(error) {
                        console.log(error)
                    })
                  },
                }
              }
</script>
javascript vue.js axios splice
1个回答
-1
投票

这里的id实际上是指数,而不是真正的post.id,而splice()采用起始指数,请参阅签名here

<li v-for="(post, id) of posts">
<!----------------^^--- This is essentially posts[index] -->

因此,请尝试执行以下操作:

<template>
  <div id="app">
    <ul>
      <li v-for="(post, index) of posts">
        <p>{{ post.title }}</p>
        <p>{{ post.body }}</p>
        <button @click="deleteData(index, post.id)">Delete</button>
      </li>
    </ul>
  </div>
</template>
methods: {
  deleteData(index, id) {
    axios
      .delete('http://jsonplaceholder.typicode.com/posts/' + id)
      .then(response => {
        this.posts.splice(index, 1);
      })
      .catch(function (error) {
        console.log(error)
      })
  },
}
© www.soinside.com 2019 - 2024. All rights reserved.