列表项从下到上删除,但不是从上到下
List items are removed from bottom to top but not from top to bottom
我列出了在 link 上拍摄的物品。在每个元素附近都有一个要删除的按钮,单击该按钮应将元素从站点中删除 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>
这里的id
实际上是索引,不是真正的post.id
,而splice()
takes a start index, see the signature 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)
})
},
}
我列出了在 link 上拍摄的物品。在每个元素附近都有一个要删除的按钮,单击该按钮应将元素从站点中删除 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>
这里的id
实际上是索引,不是真正的post.id
,而splice()
takes a start index, see the signature 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)
})
},
}