vue前端项目实战案例
时间: 2023-07-29 10:11:03 浏览: 115
当然!这里有一个简单的 Vue 前端项目实战案例:一个待办事项列表应用。
首先,创建一个新的 Vue 项目:
```bash
vue create todo-list
```
选择默认配置,然后进入项目目录:
```bash
cd todo-list
```
安装所需的依赖项:
```bash
npm install axios
```
然后,创建一个名为 `TodoList.vue` 的组件文件,并在其中添加以下代码:
```html
<template>
<div>
<h1>Todo List</h1>
<input v-model="task" placeholder="Add a new task" />
<button @click="addTask">Add Task</button>
<ul>
<li v-for="(task, index) in tasks" :key="index">
{{ task }}
<button @click="deleteTask(index)">Delete</button>
</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
task: '',
tasks: [],
};
},
methods: {
async addTask() {
if (this.task.trim() !== '') {
try {
const response = await axios.post('/api/tasks', {
task: this.task,
});
this.tasks.push(response.data.task);
this.task = '';
} catch (error) {
console.error(error);
}
}
},
async deleteTask(index) {
try {
await axios.delete(`/api/tasks/${index}`);
this.tasks.splice(index, 1);
} catch (error) {
console.error(error);
}
},
},
};
</script>
<style scoped>
button {
margin-left: 5px;
}
</style>
```
接下来,创建一个名为 `index.js` 的文件来设置路由和启动服务:
```javascript
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const tasks = [];
app.get('/api/tasks', (req, res) => {
res.json(tasks);
});
app.post('/api/tasks', (req, res) => {
const { task } = req.body;
tasks.push(task);
res.json({ task });
});
app.delete('/api/tasks/:index', (req, res) => {
const { index } = req.params;
tasks.splice(index, 1);
res.json({ index });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
```
最后,在根组件 `App.vue` 中导入并使用 `TodoList` 组件:
```html
<template>
<div id="app">
<TodoList />
</div>
</template>
<script>
import TodoList from './components/TodoList.vue';
export default {
components: {
TodoList,
},
};
</script>
<style>
#app {
margin: 20px;
}
</style>
```
现在,你可以运行该项目并在浏览器中查看结果:
```bash
npm run serve
```
这是一个简单的待办事项列表应用,你可以添加和删除任务。请注意,这只是一个基本的示例,你可以根据自己的需求进行扩展和改进。希望对你有所帮助!