vue3组合式实现代办事项程序开发
时间: 2023-12-03 11:40:47 浏览: 82
基于vue开发的待办事项demo
以下是使用Vue3组合式API实现代办事项程序的示例代码:
```html
<template>
<div>
<h2>Todo List</h2>
<form @submit.prevent="addTodo">
<input type="text" v-model="newTodo" placeholder="Add a new todo">
<button>Add</button>
</form>
<ul>
<li v-for="(todo, index) in todos" :key="index">
<input type="checkbox" v-model="todo.completed">
<span :class="{ completed: todo.completed }">{{ todo.text }}</span>
<button @click="removeTodo(index)">Remove</button>
</li>
</ul>
</div>
</template>
<script>
import { reactive, computed } from 'vue'
export default {
setup() {
const state = reactive({
todos: [
{ text: 'Learn Vue 3', completed: false },
{ text: 'Build a todo app', completed: false },
{ text: 'Learn Composition API', completed: false }
],
newTodo: ''
})
const addTodo = () => {
if (state.newTodo.trim() !== '') {
state.todos.push({ text: state.newTodo, completed: false })
state.newTodo = ''
}
}
const removeTodo = index => {
state.todos.splice(index, 1)
}
const completedTodos = computed(() => {
return state.todos.filter(todo => todo.completed)
})
return {
state,
addTodo,
removeTodo,
completedTodos
}
}
}
</script>
<style>
.completed {
text-decoration: line-through;
}
</style>
```
在这个示例中,我们使用了Vue3的组合式API来实现代办事项程序。我们使用了`reactive`函数来创建一个响应式的状态对象,其中包含了一个`todos`数组和一个`newTodo`字符串。我们还使用了`computed`函数来计算已完成的任务数量。我们在`setup`函数中定义了`addTodo`和`removeTodo`方法来添加和删除任务。最后,我们将这些方法和状态对象暴露给模板,以便在模板中使用。
阅读全文