【问题标题】:List items are removed from bottom to top but not from top to bottom列表项从下到上删除,但不是从上到下
【发布时间】:2019-07-24 08:16:00
【问题描述】:

我列出了链接上的项目。在每个元素附近都有一个按钮,当单击该按钮时,应从站点和 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>

【问题讨论】:

  • 您应该在删除帖子后立即重新获取帖子。您的索引在您所谓的“站点”和上面提供的代码中的 api 之间变得不同步。
  • 你能告诉我该怎么做吗?
  • 删除帖子的更好方法是手动获取索引(例如findIndex),而不是尝试将索引与id:stackoverflow.com/a/49689914/3499595链接
  • 替换:this.posts.splice(id-1,1)this.created();,完成。

标签: javascript vue.js axios splice


【解决方案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)
      })
  },
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    相关资源
    最近更新 更多