我正在从Vue的Options API过渡到 Composition API,为此,我制作了一个小型Todo App。
在App.vue
中,我有:
<template>
<div id="app">
<ErrorMessage
v-if="!isValid"
message="The todo body has to be at least 3 characters long"
/>
<SuccessMessage v-if="allDone" message="You can relex! :)" />
<p>{{ allDone }}</p>
<div class="card">
<Header />
<List
:todos="todos"
@delete-todo="deleteTodo"
@toggle-todo="toggleTodo"
/>
<AddTodo @add-todo="addTodo" />
</div>
</div>
</template>
<script>
import { ref, computed } from 'vue';
import ErrorMessage from './components/ErrorMessage.vue';
import SuccessMessage from './components/SuccessMessage.vue';
import Header from './components/Header.vue';
import List from './components/List.vue';
import AddTodo from './components/Add.vue';
export default {
name: 'App',
components: {
ErrorMessage,
SuccessMessage,
Header,
List,
AddTodo,
},
setup() {
const todos = ref([]);
const isValid = ref(true);
const allDone = ref(false);
return { todos, isValid, allDone };
},
methods: {
toggleTodo: function (index) {
this.todos[index].done = !this.todos[index].done;
},
deleteTodo: function (index) {
if (confirm('Are you sure?')) {
this.todos.splice(index, 1);
}
},
addTodo: function (text) {
let newTodo = {
done: false,
text: text,
};
if (text.length > 2) {
this.isValid = true;
this.todos.push(newTodo);
} else {
this.isValid = false;
}
},
},
computed: {
allDone: function () {
// Check if there are todos and
// If all of them are done
let undoneTodos = this.todos.filter((todo) => todo.done === false);
return this.todos.length && !undoneTodos.length;
},
},
};
</script>
字符串
我尝试使用计算属性allDone
来检查是否有todos,并且所有todos都已完成,在这种情况下,我尝试在alert组件中显示成功消息(“You can relax!”)。
但是,allDone
变量的 * 初始值 * 在满足其更改条件时不会更改。
我做错了什么?
1条答案
按热度按时间lmyy7pcs1#
从setup函数的返回中删除
allDone
,ref将覆盖computed属性。或者,在安装程序中将其声明为计算属性,然后从计算选项中删除它:
字符串