用vue组件+vue路由+vuex+axios实现增删改查

时间: 2023-07-28 12:09:49 浏览: 47
好的,下面是一个简单的示例: 首先,安装需要的依赖: ``` npm install vue vue-router vuex axios ``` 然后,在src目录下,创建以下文件: 1. `api.js`:定义与后端交互的API请求。 2. `store.js`:定义Vuex状态管理器。 3. `router.js`:定义Vue路由器。 4. `views`目录:定义Vue组件。 `api.js`文件内容如下: ```js import axios from 'axios'; const baseUrl = 'http://localhost:3000'; // 后端API地址 const api = axios.create({ baseURL: baseUrl, timeout: 10000, }); export default { async getTodos() { const response = await api.get('/todos'); return response.data; }, async addTodo(todo) { const response = await api.post('/todos', todo); return response.data; }, async updateTodo(todo) { const response = await api.put(`/todos/${todo.id}`, todo); return response.data; }, async deleteTodoById(id) { const response = await api.delete(`/todos/${id}`); return response.data; }, }; ``` `store.js`文件内容如下: ```js import Vue from 'vue'; import Vuex from 'vuex'; import api from './api'; Vue.use(Vuex); export default new Vuex.Store({ state: { todos: [], }, mutations: { setTodos(state, todos) { state.todos = todos; }, addTodo: (state, todo) => { state.todos.push(todo); }, updateTodo: (state, todo) => { const index = state.todos.findIndex((t) => t.id === todo.id); Vue.set(state.todos, index, todo); }, deleteTodoById: (state, id) => { const index = state.todos.findIndex((t) => t.id === id); state.todos.splice(index, 1); }, }, actions: { async fetchTodos({ commit }) { const todos = await api.getTodos(); commit('setTodos', todos); }, async addTodo({ commit }, todo) { const newTodo = await api.addTodo(todo); commit('addTodo', newTodo); }, async updateTodoById({ commit }, todo) { const updatedTodo = await api.updateTodo(todo); commit('updateTodo', updatedTodo); }, async deleteTodoById({ commit }, id) { await api.deleteTodoById(id); commit('deleteTodoById', id); }, }, }); ``` `router.js`文件内容如下: ```js import Vue from 'vue'; import VueRouter from 'vue-router'; import TodoList from './views/TodoList.vue'; import AddTodo from './views/AddTodo.vue'; import EditTodo from './views/EditTodo.vue'; Vue.use(VueRouter); export default new VueRouter({ routes: [ { path: '/', name: 'home', component: TodoList, }, { path: '/add', name: 'add', component: AddTodo, }, { path: '/edit/:id', name: 'edit', component: EditTodo, }, ], }); ``` 最后,`views`目录下的组件分别为: 1. `TodoList.vue`:展示所有待办事项。 2. `AddTodo.vue`:添加新待办事项。 3. `EditTodo.vue`:编辑已有待办事项。 `TodoList.vue`文件内容如下: ```vue <template> <div> <h1>Todo List</h1> <ul> <li v-for="todo in todos" :key="todo.id"> {{ todo.title }} - {{ todo.completed ? 'Completed' : 'Not Completed' }} <router-link :to="{ name: 'edit', params: { id: todo.id }}">Edit</router-link> <button @click="deleteTodoById(todo.id)">Delete</button> </li> </ul> <router-link :to="{ name: 'add' }">Add Todo</router-link> </div> </template> <script> export default { data() { return { todos: [], }; }, async mounted() { await this.$store.dispatch('fetchTodos'); this.todos = this.$store.state.todos; }, methods: { async deleteTodoById(id) { await this.$store.dispatch('deleteTodoById', id); }, }, }; </script> ``` `AddTodo.vue`文件内容如下: ```vue <template> <div> <h1>Add Todo</h1> <form @submit.prevent="addTodo"> <label for="title">Title:</label> <input type="text" id="title" v-model="title" required /> <br /> <label for="completed">Completed:</label> <input type="checkbox" id="completed" v-model="completed" /> <br /> <button type="submit">Add</button> </form> </div> </template> <script> export default { data() { return { title: '', completed: false, }; }, methods: { async addTodo() { const todo = { title: this.title, completed: this.completed, }; await this.$store.dispatch('addTodo', todo); this.$router.push('/'); }, }, }; </script> ``` `EditTodo.vue`文件内容如下: ```vue <template> <div> <h1>Edit Todo</h1> <form @submit.prevent="updateTodo"> <label for="title">Title:</label> <input type="text" id="title" v-model="todo.title" required /> <br /> <label for="completed">Completed:</label> <input type="checkbox" id="completed" v-model="todo.completed" /> <br /> <button type="submit">Save</button> </form> </div> </template> <script> export default { data() { return { todo: {}, }; }, async mounted() { const id = this.$route.params.id; const todos = this.$store.state.todos; this.todo = todos.find((t) => t.id === Number(id)) || {}; }, methods: { async updateTodo() { await this.$store.dispatch('updateTodoById', this.todo); this.$router.push('/'); }, }, }; </script> ``` 到此为止,使用Vue组件+Vue路由+Vuex+Axios实现增删改查的示例完成了。

相关推荐

最新推荐

recommend-type

vue-router+vuex addRoutes实现路由动态加载及菜单动态加载

本篇文章主要介绍了vue-router+vuex addRoutes实现路由动态加载及菜单动态加载,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
recommend-type

vue 实现axios拦截、页面跳转和token 验证

第一步: 路由 多添加一个自定义字段 requireAuth path: '/repository', name: 'repository', meta: { requireAuth: true, // 添加该字段,表示进入这个路由是需要登录的 }, component: Repository 第二步: ...
recommend-type

pre_o_1csdn63m9a1bs0e1rr51niuu33e.a

pre_o_1csdn63m9a1bs0e1rr51niuu33e.a
recommend-type

matlab建立计算力学课程的笔记和文件.zip

matlab建立计算力学课程的笔记和文件.zip
recommend-type

FT-Prog-v3.12.38.643-FTD USB 工作模式设定及eprom读写

FT_Prog_v3.12.38.643--FTD USB 工作模式设定及eprom读写
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

2. 通过python绘制y=e-xsin(2πx)图像

可以使用matplotlib库来绘制这个函数的图像。以下是一段示例代码: ```python import numpy as np import matplotlib.pyplot as plt def func(x): return np.exp(-x) * np.sin(2 * np.pi * x) x = np.linspace(0, 5, 500) y = func(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.title('y = e^{-x} sin(2πx)') plt.show() ``` 运行这段
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。