带有Vue.js和Node.js的简单购物车
时间: 2023-11-16 14:04:27 浏览: 161
好的,以下是一个简单的购物车应用程序,使用Vue.js和Node.js进行构建:
前端:
1. 创建Vue.js项目:可以使用Vue CLI进行创建,输入以下命令:
```
vue create shopping-cart
```
2. 安装必要的依赖项:
```
npm install axios vue-router vuex bootstrap-vue
```
3. 创建组件:
- App.vue:主组件,包含路由和导航栏
- Home.vue:主页组件,用于显示产品列表,并允许用户将产品添加到购物车
- Cart.vue:购物车组件,用于显示已添加到购物车的产品,并允许用户更改数量或删除产品
4. 创建路由:
在main.js文件中,使用以下代码创建路由:
```javascript
import VueRouter from 'vue-router'
import Home from './components/Home.vue'
import Cart from './components/Cart.vue'
const routes = [
{ path: '/', component: Home },
{ path: '/cart', component: Cart }
]
const router = new VueRouter({
routes
})
new Vue({
router,
render: h => h(App),
}).$mount('#app')
```
5. 创建Vuex store:
在store.js文件中,使用以下代码创建store:
```javascript
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
cart: []
},
mutations: {
addToCart(state, product) {
const item = state.cart.find(item => item.id === product.id)
if (item) {
item.quantity++
} else {
state.cart.push({...product, quantity: 1})
}
},
removeFromCart(state, product) {
const index = state.cart.findIndex(item => item.id === product.id)
state.cart.splice(index, 1)
},
updateQuantity(state, {product, quantity}) {
const item = state.cart.find(item => item.id === product.id)
item.quantity = quantity
}
},
actions: {
addToCart({commit}, product) {
commit('addToCart', product)
},
removeFromCart({commit}, product) {
commit('removeFromCart', product)
},
updateQuantity({commit}, {product, quantity}) {
commit('updateQuantity', {product, quantity})
}
},
getters: {
cartTotal(state) {
return state.cart.reduce((total, item) => total + item.price * item.quantity, 0)
},
cartItemCount(state) {
return state.cart.reduce((total, item) => total + item.quantity, 0)
}
}
})
```
6. 创建API服务:
使用Node.js和Express创建一个简单的API,用于获取产品列表:
```javascript
const express = require('express')
const app = express()
const products = [
{ id: 1, name: 'Product 1', price: 10 },
{ id: 2, name: 'Product 2', price: 20 },
{ id: 3, name: 'Product 3', price: 30 },
{ id: 4, name: 'Product 4', price: 40 }
]
app.get('/api/products', (req, res) => {
res.json(products)
})
app.listen(3000, () => {
console.log('Server listening on port 3000')
})
```
7. 使用Axios获取数据:
在Home.vue组件中,使用Axios获取产品列表,并将其显示在页面上:
```javascript
<template>
<div class="container">
<div class="row">
<div class="col-sm-4" v-for="product in products" :key="product.id">
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ product.name }}</h5>
<p class="card-text">{{ product.price }}</p>
<button class="btn btn-primary" @click="addToCart(product)">Add to Cart</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
import { mapActions } from 'vuex'
export default {
name: 'Home',
methods: {
...mapActions(['addToCart']),
async getProducts() {
const response = await axios.get('/api/products')
this.products = response.data
}
},
data() {
return {
products: []
}
},
mounted() {
this.getProducts()
}
}
</script>
```
8. 在Cart.vue组件中显示购物车:
在Cart.vue组件中,使用Vuex store中的数据显示已添加到购物车的产品,并允许用户更改数量或删除产品:
```javascript
<template>
<div class="container">
<div class="row">
<div class="col-sm-8">
<div class="card mb-3" v-for="item in cart" :key="item.id">
<div class="card-body">
<h5 class="card-title">{{ item.name }}</h5>
<p class="card-text">{{ item.price * item.quantity }}</p>
<div class="input-group mb-3">
<div class="input-group-prepend">
<button class="btn btn-outline-secondary" type="button" @click="decrementQuantity(item)">-</button>
</div>
<input type="text" class="form-control" :value="item.quantity" @input="updateQuantity(item, $event.target.value)">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" @click="incrementQuantity(item)">+</button>
</div>
</div>
<button class="btn btn-danger" @click="removeFromCart(item)">Remove</button>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="card">
<div class="card-body">
<h5 class="card-title">Cart Summary</h5>
<p class="card-text">Total items: {{ cartItemCount }}</p>
<p class="card-text">Total price: {{ cartTotal }}</p>
<router-link to="/" class="btn btn-primary">Continue Shopping</router-link>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
name: 'Cart',
computed: {
...mapState(['cartTotal', 'cartItemCount']),
cart() {
return this.$store.state.cart
}
},
methods: {
...mapActions(['removeFromCart', 'updateQuantity']),
incrementQuantity(product) {
this.updateQuantity({product, quantity: product.quantity + 1})
},
decrementQuantity(product) {
if (product.quantity > 1) {
this.updateQuantity({product, quantity: product.quantity - 1})
}
}
}
}
</script>
```
后端:
1. 创建Node.js项目:
在命令行中,输入以下命令创建一个新的Node.js项目:
```
mkdir shopping-cart-backend
cd shopping-cart-backend
npm init -y
```
2. 安装必要的依赖项:
```
npm install express cors
```
3. 创建API服务:
在index.js文件中,使用以下代码创建API服务:
```javascript
const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors())
const products = [
{ id: 1, name: 'Product 1', price: 10 },
{ id: 2, name: 'Product 2', price: 20 },
{ id: 3, name: 'Product 3', price: 30 },
{ id: 4, name: 'Product 4', price: 40 }
]
app.get('/api/products', (req, res) => {
res.json(products)
})
app.listen(3000, () => {
console.log('Server listening on port 3000')
})
```
4. 启动API服务:
在命令行中,输入以下命令启动API服务:
```
node index.js
```
现在,您可以在浏览器中访问http://localhost:3000/api/products,以获取产品列表。
完成以上步骤后,您可以使用以下命令启动Vue.js应用程序:
```
npm run serve
```
然后,您可以在浏览器中访问http://localhost:8080,以查看并测试购物车应用程序。
阅读全文