Vue中TodoList案例_本地存储
发布人:shili8
发布时间:2025-02-17 01:06
阅读次数:0
**Vue 中 TodoList 案例**
在 Vue 的学习过程中,TodoList 是一个经典的案例,它可以帮助我们理解 Vue 的核心概念,如数据绑定、事件处理等。同时,TodoList 也可以演示如何使用本地存储来保存数据。
###1. 创建项目首先,我们需要创建一个新的 Vue项目。这里我们使用 Vue CLI 来快速创建一个新项目。
bashnpm install -g @vue/clivue create todo-list
选择 "Manually select features",然后选择 "Babel", "PWA", "Router", "Vuex" 等选项。
###2. 创建 TodoList 组件接下来,我们需要创建一个 TodoList 组件。这个组件将负责显示和管理 TodoList 的数据。
bashcd todo-listnpm run serve
在 `src` 目录下新建 `TodoList.vue` 文件:
html<template> <div> <h1>Todo List</h1> <input v-model="newTodo" @keyup.enter="addTodo"> <ul> <li v-for="(todo, index) in todos" :key="index"> {{ todo }} <button @click="removeTodo(index)">删除</button> </li> </ul> </div> </template> <script> export default { data() { return { newTodo: '', todos: [] } }, methods: { addTodo() { this.todos.push(this.newTodo) this.newTodo = '' }, removeTodo(index) { this.todos.splice(index,1) } } } </script>
###3. 使用 Vuex 来管理状态在上面的例子中,我们使用了 Vue 的内置数据绑定功能来保存 TodoList 的数据。但是,这种方式有一个缺点:当我们切换路由时,TodoList 的数据会丢失。
为了解决这个问题,我们可以使用 Vuex 来管理状态。Vuex 是一个状态管理库,它可以帮助我们在应用中共享和管理状态。
bashnpm install vuex
在 `src` 目录下新建 `store.js` 文件:
javascriptimport Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { todos: [] }, mutations: { ADD_TODO(state, todo) { state.todos.push(todo) }, REMOVE_TODO(state, index) { state.todos.splice(index,1) } } }) export default store
###4. 使用本地存储来保存数据最后,我们需要使用本地存储来保存 TodoList 的数据。我们可以使用 `localStorage` API 来实现这一点。
javascriptimport { store } from './store' const todos = JSON.parse(localStorage.getItem('todos')) || [] store.state.todos = todosstore.watch((state) => state.todos, (newTodos) => { localStorage.setItem('todos', JSON.stringify(newTodos)) })
###5. 测试和部署最后,我们需要测试和部署我们的应用。我们可以使用 `npm run test` 来运行单元测试,或者使用 `npm run build` 来构建生产环境的代码。
当我们完成了所有这些步骤后,我们就可以在浏览器中打开我们的 TodoList 应用了!
### 总结本文介绍了如何在 Vue 中创建一个 TodoList 案例,并使用 Vuex 和本地存储来管理状态。通过阅读本文,读者应该能够理解 Vue 的核心概念,如数据绑定、事件处理等,以及如何使用 Vuex 和本地存储来保存和管理应用的状态。
### 参考* [Vue.js]( />* [Vuex]( />* [localStorage API](