【问题标题】:Why does delete method not updated the list?为什么删除方法不更新列表?
【发布时间】: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)
        }
    }

【问题讨论】:

标签: mongodb vue.js vuex


【解决方案1】:

只是浏览一下,您似乎正在等待异步方法并且也在执行 .then。 如果您正在等待一个方法,那么该任务将等到它完成承诺,然后再转到下一行。 (more info on async/await here)

此外,我不确定您在调度“DELETE_TASK”时是否返回了响应。我看到在该方法中调用了“SET_MESSAGE”。你可以随时查看我的 console.logging。 如果是这种情况,请尝试如下更改 delete todo 方法

async deletetodo(id){
           
           try{
           let response = await this.$store.dispatch("DELETE_TASK",{'id':id});
           this.$store.dispatch("GET_TASK");
                console.log(response);
            }
            catch(error){
            console.log(`DeleteTodo ${error}`)
            }
        }

编码愉快!

【讨论】:

    【解决方案2】:

    我必须通过添加 DELETE METHOD 来解决这个问题

    vuex:

    async DELETE_TASK({ commit }, obj) {
        try {
            const id = obj['id']
            const raw = await fetch(`http://localhost:3000/delete/${id}`, {
                method: 'DELETE',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ 'id': id })
            });
            const content = await raw.json();
            commit("SET_MESSAGE", content)
        } catch (error) {
            console.log(`DELETE_TASK ${error}`)
        }
    }
    

    server.js

    app.delete('/delete/:id', async(req, res) => {
        try {
            const id = req.body.id;
            TodoTask.findByIdAndDelete(id, err => {
                if (err) return res.send(500, err);
                res.send({ 'status': 200, "mensagem": 'Tarefa deletada' })
            })
        } catch (error) {
            console.log(`Error Delete ${error}`)
        }
    })
    

    ListTodo.vue

    methods:{        
        async deletetodo(id){
            try{
                await this.$store.dispatch("DELETE_TASK",{'id':id})
                .then(response => {
                    this.$store.dispatch("GET_TASK");
                    console.log(response);
                }) 
                .catch(error => console.log(error))
            }catch(error){
                console.log(`DeleteTodo ${error}`);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多