【发布时间】:2020-12-27 16:09:32
【问题描述】:
使用 VueJS、Vuex 和 MongoDB 的工作 Todo 应用程序,删除任务后,我的列表在没有刷新页面的情况下不会更新。我已经在等待列表更新的承诺中添加了一个调度GET_TASK,但它不起作用,而且似乎这个承诺甚至没有执行。
<template>
<div class="flex-col mx-auto mt-10 min-w-max font-sans text-xl" style="width:512px">
<ul class="space-y-2">
<li class="flex justify-between px-4 min-h-full" v-for="task in tasks" :key="task.id">
{{task.task}}
<button @click="deletetodo(task._id)" class="text-xs border-2 px-4 focus:outline-none hover:bg-blue-200 hover:text-white rounded-full">Delete</button>
</li>
</ul>
</div>
</template>
<script>
export default {
name:"ListToDo",
computed:{
tasks: function(){
return this.$store.state.task
}
},
methods:{
async getlisttodo(){
await this.$store.dispatch("GET_TASK")
},
async deletetodo(id){
await this.$store.dispatch("DELETE_TASK",{'id':id})
.then(response => {
this.$store.dispatch("GET_TASK")
console.log(response);
})
.catch(error => console.log(`DeleteTodo ${error}`))
}
},
mounted(){
this.getlisttodo()
}
}
</script>
Vuex:
actions: {
async GET_TASK({ commit }) {
const rawResponse = await fetch('http://localhost:3000/tasks')
const content = await rawResponse.json();
commit("SET_TASK", content)
},
async SAVE_TASK({ commit }, object) {
const rawResponse = await fetch('http://localhost:3000/save', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ 'task': object })
});
const content = await rawResponse.json();
commit("SET_MESSAGE", content)
},
async DELETE_TASK({ commit }, obj) {
const id = obj['id']
const raw = await fetch(`http://localhost:3000/delete/${id}`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ 'id': id })
});
const content = await raw.json();
commit("SET_MESSAGE", content)
}
}
【问题讨论】:
-
你为什么不在你的突变中做一个
splice -
什么意思?
-
您可以使用
array splicedeveloper.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 删除 Vuex Mutations 中的数组。所以你需要创建新的突变,例如“DELETE_MESSAGE” -
我想你也需要从
raw.json()中删除await