Im writing a Todo App in VueJS, with two components NewTask
and TodoList
NewTask:
<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>
Todolist:
<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)
}
}
})
What am I missing/forgeting for updating without refresh page?
In your NewTask component, inside add task method do like this.
await this.$store.dispatch("SAVE_TASK",task).then((response)=>{
this.$store.dispatch("GET_TASK")
this.task = ''
}).catch(error=>{
console.log(error)
})