首页 > 解决方案 > 为什么我的组件没有刷新页面就不会更新?

问题描述

我在 VueJS 中编写了一个 Todo 应用程序,它有两个组件NewTaskTodoList

新任务:

<template>
         <!-- New Task -->
         <div class="flex flex-col"> 
           <div class="flex-col">
              <textarea class="resize-none rounded-md font-sans font-bold p-4 focus:outline-none border" v-model="task" placeholder="Task" cols="40" rows="2"></textarea>
           </div>
           <div class="flex-col py-2">
              <button @click="AddTask(task)" class="py-4 px-20 focus:outline-none  bg-blue-200 rounded-full">Add</button>
           </div>
         </div>
        
         <!-- End Component -->
</template>

<script>
export default {
    name:"NewTask",
    data(){
       return{
         task: ''
       }
    },
    methods:{
       async AddTask(task){
          await this.$store.dispatch("SAVE_TASK",task)
          this.task = ''          
       }
    }
    
}
</script>

待办事项列表:

<template>
    <div class="flex-col mx-auto min-w-max font-sans text-xl" style="width:512px">
        <ul class="space-y-2">
            <li class="text-left border-2 px-4 min-h-full" v-for="task in tasks" :key="task.id">{{task.task}} </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")
        }
    },
    mounted(){
        this.getlisttodo()
    }
}
</script>

Vuex:

export default new Vuex.Store({
    state: {
        task: [],
        message: []
    },

    mutations: {
        SET_TASK: function(state, task) {
            state.task = task
        },
        SET_MESSAGE: function(state, message) {
            state.message = message
        }
    },

    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)
        }
    }
})

在没有刷新页面的情况下更新我错过/忘记了什么?

标签: vue.jsvuex

解决方案


在您的 NewTask 组件中,在 add task 方法中这样做。

await this.$store.dispatch("SAVE_TASK",task).then((response)=>{
this.$store.dispatch("GET_TASK")
this.task = '' 
 }).catch(error=>{
console.log(error)
})
     

推荐阅读