已解决:在函数中添加this.tasks = resp.data,以便更新到新状态...
我目前正在使用vuejs中的一个简单的待办事项列表应用程序,我正在寻找一种在执行api请求后以平滑的方式更新dom的方法。我能够在完成更改后直接显示更改的唯一方法是在响应中放置location.reload()。我一直在查看一些示例和指南,人们似乎可以使用.bind()来完成此操作,但它并不适用于我,并且我不满足于每次更改时页面闪烁。
//deletePost works for displaying changes but i don't want the page to flash on every update
deletePost(id) {
axios.delete(`http://localhost:3000/tasks/${id}`)
.then((resp) => {
console.log(resp.data)
location.reload();
})
.catch((err) => {
console.log(err)
})
},
//this is how i've seen people doing it, but it's not working for me.
updatePost(selected, id) {
axios.put(`http://localhost:3000/tasks/${id}`,{ status: selected } )
.then(function(response){
console.log('saved successfully')
}.bind(this));
}
},
有什么想法吗?
答案 0 :(得分:0)
你在Vue组件中有一系列任务。发送http请求会从服务器中删除资源,但不会在本地删除。要删除组件中的资源,您需要在.then()部分中执行此操作,例如:
data() return {
tasks: []
},
deletePost(id) {
axios.delete(`http://localhost:3000/tasks/${id}`)
.then((resp) => {
console.log(resp.data)
// Here we delete the task from the component locally
// Note that we only want to delete it if the request is successful
let index= this.tasks.find(task => task.id === id)
this.tasks.splice(index,1);
})
.catch((err) => {
console.log(err)
})
},
//this is how i've seen people doing it, but it's not working for me.
updatePost(selected, id) {
axios.put(`http://localhost:3000/tasks/${id}`,{ status: selected } )
.then(function(response){
console.log('saved successfully')
}.bind(this));
}
},
答案 1 :(得分:0)
感谢您在这里快速回复我的第一篇文章,当然我应该提供整个脚本而不仅仅是api请求...
data () {
return {
tasks: [],
formValue: '',
selected: ''
}
},
created () {
this.fetchData()
},
watch: {
'$route': 'fetchData',
},
methods: {
fetchData () {
axios.get('http://localhost:3000/tasks')
.then((resp) => {
this.tasks = resp.data
console.log(resp.data)
})
.catch((err) => {
console.log(err)
})
},
deletePost(id) {
axios.delete(`http://localhost:3000/tasks/${id}`)
.then((resp) => {
console.log(resp.data)
// Here we delete the task from the component locally
// Note that we only want to delete it if the request is successful
let index= this.tasks.find(task => task.id === id)
this.tasks.splice(index,1);
})
.catch((err) => {
console.log(err)
})
},
//updates post status
updatePost(selected, id) {
axios.put(`http://localhost:3000/tasks/${id}`,{ status: selected } )
.then(function(response){
console.log('saved successfully')
}.bind(this));
}
},
}