vue商城实现
环境搭建与项目初始化
使用 Vue CLI 快速初始化项目,确保已安装 Node.js 和 npm/yarn。
npm install -g @vue/cli
vue create vue-mall
cd vue-mall
npm install vue-router vuex axios --save
路由配置
在 src/router/index.js 中配置基本路由,包括首页、商品列表、详情页和购物车。
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
const routes = [
{ path: '/', component: Home },
{ path: '/product/:id', component: () => import('../views/ProductDetail.vue') }
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
状态管理(Vuex)
创建 src/store/index.js 管理购物车和用户状态。

import { createStore } from 'vuex';
export default createStore({
state: {
cart: []
},
mutations: {
addToCart(state, product) {
state.cart.push(product);
}
}
});
商品列表与详情页
通过 axios 获取后端 API 数据,展示商品列表和详情。
// 在组件中调用API
import axios from 'axios';
export default {
data() {
return { products: [] };
},
async created() {
const res = await axios.get('/api/products');
this.products = res.data;
}
};
购物车功能
在购物车组件中调用 Vuex 的 addToCart 方法,实时更新状态。

<template>
<button @click="addToCart(product)">加入购物车</button>
</template>
<script>
export default {
methods: {
addToCart(product) {
this.$store.commit('addToCart', product);
}
}
};
</script>
支付与订单提交
集成第三方支付接口(如支付宝/微信支付),提交订单数据到后端。
async submitOrder() {
const res = await axios.post('/api/orders', { cart: this.$store.state.cart });
if (res.data.success) {
window.location.href = res.data.paymentUrl;
}
}
部署上线
使用 npm run build 生成静态文件,部署到 Nginx 或云服务(如 Vercel)。
npm run build
# 将dist目录上传至服务器
注意事项
- 接口需配置跨域支持(CORS)。
- 生产环境需启用 HTTPS 确保支付安全。
- 商品图片建议使用 CDN 加速加载。






