【发布时间】:2019-03-13 12:17:31
【问题描述】:
我正在尝试在 Vue 中创建一个简单的待办事项列表,但我想将所有内容抽象出来并使用一个虚拟 REST API,这样我就可以开始习惯 Vue 中的生产级项目,这一切都让我头晕目眩。 GET、PUT 和 POST 请求似乎正常工作,但我无法弄清楚为什么当我向后端发出成功的 POST 请求时,todos 列表没有自动更新。
我有一个 TodoList 组件,它循环通过 todosFiltered() 计算属性来显示待办事项。计算的属性返回到 Vuex 存储中的 getter todosFiltered。我还在这里使用created() 生命周期钩子在商店中调度一个操作,该操作发出初始GET 请求,然后在页面首次加载时在商店中填充一个名为todos 的数组。商店中的getter todosFiltered 返回state.todos,所以我假设当我的组件重新渲染时,它会从todosFiltered 中抓取状态中的新todos 数组,只是没有发生。我在这里想念什么?任何建议将不胜感激。
TodoList.vue
(我知道我必须为 id 制定一个解决方案,它在我的列表中:p)
<template>
<div class="container">
<input v-model="newTodo" type="text" placeholder="What must be done?" class="todo-input" @keyup.enter="addTodo">
<transition-group name="fade" enter-active-class="animated zoomIn" leave-active-class="animated zoomOut">
<todo-item v-for="todo in todosFiltered" :key="todo.id" :checkAll="!anyRemaining" :todo="todo"></todo-item>
</transition-group>
<div class="extra-container">
<todos-filtered></todos-filtered>
</div>
</div>
</template>
<script>
import TodosFiltered from './TodosFiltered'
import TodoItem from './TodoItem'
export default {
name: 'todolist',
components: {
TodosFiltered,
TodoItem
},
data() {
return {
beforeEditCache: '',
newTodo: '',
idForTodo: 10,
}
},
// Methods
methods: {
addTodo() {
if (this.newTodo.trim().length == 0) {
return
}
this.$store.dispatch('addTodo', {
id: this.idForTodo,
title: this.newTodo,
completed: false
})
this.newTodo = ''
this.idForTodo++
}
},
computed: {
todosFiltered() {
return this.$store.getters.todosFiltered
},
},
created() {
this.$store.dispatch('loadTodos')
},
}
</script>
store.js
export const store = new Vuex.Store({
state: {
filter: 'all',
todos: []
},
getters: {
todosFiltered(state) {
if (state.filter == 'all') {
return state.todos
} else if (state.filter == 'active') {
return state.todos.filter(todo => !todo.completed)
} else if (state.filter == 'completed') {
return state.todos.filter(todo => todo.completed)
}
return state.todos
},
showClearCompleted(state) {
return state.todos.filter(todo => todo.completed).length > 0
}
},
mutations: {
addTodo(state, todo) {
state.todos.push(todo)
},
setTodos(state, todos) {
state.todos = todos
},
},
actions: {
loadTodos(context) {
axios.get('http://localhost:3000/todos')
.then(r => r.data)
.then(todos => {
context.commit('setTodos', todos)
})
},
updateTodo(context, todo) {
axios.put('http://localhost:3000/todos/' + todo.id, {
"id": todo.id,
"title": todo.title,
"completed": todo.completed
})
},
addTodo(context, todo) {
axios.post('http://localhost:3000/todos', {
"id": todo.id,
"title": todo.title,
"completed": todo.completed
})
.then(todo => {
context.commit('addTodo', todo)
})
},
}
})
编辑:当我添加待办事项时,Vue 开发工具中发生了以下情况——商店状态中的 todos 立即更新,TodoList 组件中的 todosFiltered 计算属性也反映了这一点——但是新的待办事项没有出现在列表中!奇怪。
【问题讨论】:
-
在这里使用计算属性将不起作用。因为计算属性不依赖于 Vue 实例中的任何属性。在这里阅读更多:vuejs.org/v2/guide/computed.html#Computed-Caching-vs-Methods
-
就像@DuongDang 说的那样,由于缓存,它不适用于计算属性
标签: javascript vue.js