Vue.js Composition API实现TodoMVC应用解析
前言
TodoMVC是一个经典的待办事项应用实现,被广泛用于前端框架的教学和比较。本文将通过分析Vue.js官方示例中的composition/todomvc.html文件,深入探讨如何使用Vue 3的Composition API构建一个功能完整的Todo应用。
项目结构与基础配置
示例中首先引入了Vue的核心库和TodoMVC的标准CSS样式:
<script src="../../dist/vue.min.js"></script>
<link rel="stylesheet" href="../../node_modules/todomvc-app-css/index.css" />
这种配置方式确保了应用具有统一的外观和行为,符合TodoMVC项目的规范要求。
响应式状态管理
核心的状态管理使用了Vue 3的Composition API:
const { reactive, computed, watchEffect, onMounted, onUnmounted } = Vue
状态初始化
应用状态通过reactive
函数创建响应式对象:
const state = reactive({
todos: todoStorage.fetch(),
editedTodo: null,
newTodo: '',
beforeEditCache: '',
visibility: 'all',
// 计算属性...
})
计算属性
示例中展示了多种计算属性的使用方式:
- 剩余待办项数量:
remaining: computed(() => {
return filters.active(state.todos).length
})
- 复数形式文本:
remainingText: computed(() => {
return ` ${pluralize(state.remaining)} left`
})
- 过滤后的待办项:
filteredTodos: computed(() => {
return filters[state.visibility](state.todos)
})
- 全选/全不选功能:
allDone: computed({
get: function () {
return state.remaining === 0
},
set: function (value) {
state.todos.forEach(todo => {
todo.completed = value
})
}
})
数据持久化
应用实现了本地存储功能,确保数据在页面刷新后不丢失:
const STORAGE_KEY = 'todos-vuejs-3.x-composition'
const todoStorage = {
fetch() {
const todos = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]')
todos.forEach((todo, index) => {
todo.id = index
})
todoStorage.uid = todos.length
return todos
},
save(todos) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(todos))
}
}
通过watchEffect
自动监听状态变化并保存:
watchEffect(() => {
todoStorage.save(state.todos)
})
核心功能实现
添加待办项
function addTodo() {
const value = state.newTodo && state.newTodo.trim()
if (!value) return
state.todos.push({
id: todoStorage.uid++,
title: value,
completed: false
})
state.newTodo = ''
}
编辑功能
实现了双击编辑、回车确认、ESC取消等完整编辑流程:
function editTodo(todo) {
state.beforeEditCache = todo.title
state.editedTodo = todo
}
function doneEdit(todo) {
if (!state.editedTodo) return
state.editedTodo = null
todo.title = todo.title.trim()
if (!todo.title) removeTodo(todo)
}
function cancelEdit(todo) {
state.editedTodo = null
todo.title = state.beforeEditCache
}
路由过滤
通过监听hash变化实现不同状态待办项的过滤:
function onHashChange() {
const visibility = window.location.hash.replace(/#\/?/, '')
if (filters[visibility]) {
state.visibility = visibility
} else {
window.location.hash = ''
state.visibility = 'all'
}
}
自定义指令
实现了一个自动聚焦的自定义指令:
directives: {
'todo-focus': (el, { value }) => {
if (value) {
el.focus()
}
}
}
生命周期管理
使用Composition API的生命周期钩子:
onMounted(() => {
window.addEventListener('hashchange', onHashChange)
onHashChange()
})
onUnmounted(() => {
window.removeEventListener('hashchange', onHashChange)
})
总结
这个TodoMVC示例展示了Vue 3 Composition API的核心特性:
- 使用
reactive
创建响应式状态 - 通过
computed
创建派生状态 - 利用
watchEffect
实现副作用 - 生命周期钩子的使用
- 自定义指令的应用
相比Options API,Composition API提供了更灵活的逻辑组织和复用方式,特别适合复杂组件的开发。通过这个示例,开发者可以学习到如何将传统Vue应用迁移到Composition API,以及如何利用其特性构建更健壮的应用程序。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考