用node.js和vue3搭建一个商品管理系统项目,需要有查询,修改,添加功能,给出相关代码框架。
时间: 2024-03-24 07:40:24 浏览: 18
好的,下面是用Node.js和Vue 3搭建一个商品管理系统项目的代码框架,包括查询、修改和添加功能:
### 后端代码
在后端使用Express框架,使用MongoDB数据库存储商品信息。以下是后端代码框架:
```javascript
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
// 解析JSON格式的请求体
app.use(bodyParser.json());
// 允许跨域请求
app.use(cors());
// 连接MongoDB数据库
mongoose.connect('mongodb://localhost/mydb', { useNewUrlParser: true, useUnifiedTopology: true });
// 定义商品模型
const Product = mongoose.model('Product', {
name: String,
price: Number,
description: String
});
// 查询商品列表
app.get('/api/products', async (req, res) => {
const products = await Product.find();
res.json(products);
});
// 查询单个商品
app.get('/api/products/:id', async (req, res) => {
const product = await Product.findById(req.params.id);
res.json(product);
});
// 添加商品
app.post('/api/products', async (req, res) => {
const product = new Product(req.body);
await product.save();
res.json(product);
});
// 修改商品
app.put('/api/products/:id', async (req, res) => {
const product = await Product.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.json(product);
});
// 删除商品
app.delete('/api/products/:id', async (req, res) => {
await Product.findByIdAndRemove(req.params.id);
res.json({ message: '删除成功' });
});
// 启动服务器
app.listen(3000, () => {
console.log('服务器已启动');
});
```
### 前端代码
在前端使用Vue 3框架,使用Axios库进行HTTP请求。以下是前端代码框架:
```html
<template>
<div>
<h1>商品列表</h1>
<table>
<thead>
<tr>
<th>名称</th>
<th>价格</th>
<th>描述</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="product in products" :key="product._id">
<td>{{ product.name }}</td>
<td>{{ product.price }}</td>
<td>{{ product.description }}</td>
<td>
<button @click="editProduct(product)">编辑</button>
<button @click="deleteProduct(product)">删除</button>
</td>
</tr>
</tbody>
</table>
<h1>添加商品</h1>
<form @submit.prevent="addProduct">
<div>
<label>名称:</label>
<input v-model="newProduct.name" type="text">
</div>
<div>
<label>价格:</label>
<input v-model="newProduct.price" type="number">
</div>
<div>
<label>描述:</label>
<textarea v-model="newProduct.description"></textarea>
</div>
<button type="submit">添加</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
products: [],
newProduct: {
name: '',
price: 0,
description: ''
}
};
},
mounted() {
this.loadProducts();
},
methods: {
async loadProducts() {
const response = await axios.get('/api/products');
this.products = response.data;
},
async editProduct(product) {
// 实现修改商品的逻辑
},
async deleteProduct(product) {
// 实现删除商品的逻辑
},
async addProduct() {
await axios.post('/api/products', this.newProduct);
this.newProduct = {
name: '',
price: 0,
description: ''
};
this.loadProducts();
}
}
};
</script>
```
以上就是用Node.js和Vue 3搭建商品管理系统项目的代码框架,其中的编辑和删除功能需要自己实现。希望能对你有所帮助!