vue.js - 为什么我的组件没有刷新页面就不会更新?
问题描述
我在 VueJS 中编写了一个 Todo 应用程序,它有两个组件NewTask
和TodoList
新任务:
<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)
}
}
})
在没有刷新页面的情况下更新我错过/忘记了什么?
解决方案
在您的 NewTask 组件中,在 add task 方法中这样做。
await this.$store.dispatch("SAVE_TASK",task).then((response)=>{
this.$store.dispatch("GET_TASK")
this.task = ''
}).catch(error=>{
console.log(error)
})
推荐阅读
- autoit - 如何调试“不可访问变量上使用的下标”?
- docker - jwilder/nginx-proxy 和 jrcs/letsencrypt-nginx-proxy-companion 后面的 docker 中的 gitea
- python - 生成多个列表内容的所有可能组合,其中包含自定义字符
- android - 如何在android中进行全屏布局?
- sql - LINQ 中的 where 子句子查询
- python - 在不使用循环的情况下处理三个二维 numpy 数组
- php - 重定向后刷新页面
- pandas - keras 中的多 GPU 训练到底意味着什么?
- java - 重复元素时需要从数组中打印唯一的数字组合
- typo3 - 无法登录新的 TYPO3 10.4.8