发布日期:2024年7月30日
一、系统架构设计
本教程将构建一个完整的电商平台,包含以下核心模块:
- 前台系统:商品展示与交易流程
- 后台系统:商品管理与订单处理
- 移动端适配:H5与小程序兼容方案
- 秒杀系统:高并发解决方案
- 支付系统:多支付渠道集成
技术栈:Vue2 + Vuex + ElementUI + Axios + Webpack
二、项目初始化与工程化
1. 项目创建与配置
# 使用Vue CLI创建项目
vue create mall-platform
# 安装核心依赖
cd mall-platform
npm install vuex element-ui axios
npm install -D webpack-bundle-analyzer
2. 目录结构规划
src/
├── api/ # 接口服务
├── components/ # 公共组件
│ ├── business/ # 业务组件
│ └── common/ # 通用组件
├── directives/ # 自定义指令
├── filters/ # 全局过滤器
├── mixins/ # 混入对象
├── router/ # 路由配置
├── store/ # Vuex状态
│ ├── modules/ # 模块化状态
│ └── index.js # 主入口
├── styles/ # 全局样式
├── utils/ # 工具函数
├── views/ # 页面组件
│ ├── front/ # 前台页面
│ └── admin/ # 后台页面
├── App.vue
└── main.js
三、高并发秒杀系统
1. 秒杀倒计时组件
<template>
<div class="countdown">
<span class="time-block">{{ days }}</span>天
<span class="time-block">{{ hours }}</span>:
<span class="time-block">{{ minutes }}</span>:
<span class="time-block">{{ seconds }}</span>
</div>
</template>
<script>
export default {
props: {
endTime: {
type: [String, Number],
required: true
}
},
data() {
return {
timer: null,
timeLeft: 0
}
},
computed: {
days() {
return Math.floor(this.timeLeft / (1000 * 60 * 60 * 24))
},
hours() {
return Math.floor((this.timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
},
minutes() {
return Math.floor((this.timeLeft % (1000 * 60 * 60)) / (1000 * 60))
},
seconds() {
return Math.floor((this.timeLeft % (1000 * 60)) / 1000)
}
},
mounted() {
this.startCountdown()
},
beforeDestroy() {
clearInterval(this.timer)
},
methods: {
startCountdown() {
this.timeLeft = new Date(this.endTime).getTime() - Date.now()
this.timer = setInterval(() => {
this.timeLeft -= 1000
if (this.timeLeft <= 0) {
clearInterval(this.timer)
this.$emit('countdown-end')
}
}, 1000)
}
}
}
</script>
2. 秒杀请求优化
// utils/seckill.js
export const seckillRequest = (function() {
let requesting = false
const queue = []
return function(productId) {
return new Promise((resolve, reject) => {
queue.push({ productId, resolve, reject })
if (!requesting) {
processQueue()
}
})
}
function processQueue() {
if (queue.length === 0) {
requesting = false
return
}
requesting = true
const { productId, resolve, reject } = queue.shift()
axios.post('/api/seckill', { productId })
.then(res => {
resolve(res.data)
setTimeout(processQueue, 100) // 控制请求频率
})
.catch(err => {
reject(err)
setTimeout(processQueue, 100)
})
}
})()
四、多端适配方案
1. 设备类型检测
// utils/device.js
export const deviceType = (function() {
const ua = navigator.userAgent
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(ua)
const isWeChat = /MicroMessenger/i.test(ua)
return {
isPC: !isMobile,
isMobile,
isWeChat,
isApp: ua.includes('MallApp')
}
})()
// 全局混入
Vue.mixin({
computed: {
isMobile() {
return this.$device.isMobile
}
}
})
2. 响应式布局组件
<template>
<div>
<template v-if="isMobile">
<mobile-layout>
<slot></slot>
</mobile-layout>
</template>
<template v-else>
<pc-layout>
<slot></slot>
</pc-layout>
</template>
</div>
</template>
<script>
export default {
computed: {
isMobile() {
return this.$device.isMobile
}
}
}
</script>
五、支付系统集成
1. 支付方式组件
<template>
<div class="payment-methods">
<el-radio-group v-model="selectedMethod">
<el-radio
v-for="method in methods"
:key="method.value"
:label="method.value"
>
<img :src="method.icon" :alt="method.label">
{{ method.label }}
</el-radio>
</el-radio-group>
<div v-if="selectedMethod === 'alipay'" class="qrcode-container">
<img :src="alipayQrcode">
</div>
</div>
</template>
<script>
export default {
data() {
return {
selectedMethod: 'wechat',
methods: [
{ value: 'wechat', label: '微信支付', icon: '/static/wechat.png' },
{ value: 'alipay', label: '支付宝', icon: '/static/alipay.png' }
],
alipayQrcode: ''
}
},
watch: {
selectedMethod(val) {
if (val === 'alipay') {
this.generateAlipayQrcode()
}
}
},
methods: {
async generateAlipayQrcode() {
const res = await this.$api.generateQrcode({
amount: this.$store.state.order.totalAmount,
orderId: this.$store.state.order.id
})
this.alipayQrcode = res.qrcodeUrl
}
}
}
</script>
2. 支付状态轮询
// utils/payment.js
export function checkPaymentStatus(orderId, callback) {
let attempts = 0
const maxAttempts = 30 // 最大尝试次数
const interval = 2000 // 轮询间隔
const timer = setInterval(async () => {
attempts++
const res = await axios.get(`/api/orders/${orderId}/status`)
if (res.data.status === 'paid') {
clearInterval(timer)
callback(true, res.data)
} else if (attempts >= maxAttempts) {
clearInterval(timer)
callback(false)
}
}, interval)
return () => clearInterval(timer)
}
六、性能优化实践
1. 图片懒加载指令
// directives/lazyload.js
export default {
inserted(el, binding) {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target
img.src = img.dataset.src
observer.unobserve(img)
}
})
})
el.dataset.src = binding.value
observer.observe(el)
el._observer = observer
},
unbind(el) {
if (el._observer) {
el._observer.disconnect()
}
}
}
2. 代码分割优化
// router/index.js
const routes = [
{
path: '/product/:id',
component: () => import(/* webpackChunkName: "product" */ '@/views/ProductDetail.vue')
},
{
path: '/user/center',
component: () => import(/* webpackChunkName: "user" */ '@/views/UserCenter.vue')
}
]
// vue.config.js
module.exports = {
configureWebpack: {
optimization: {
splitChunks: {
chunks: 'all',
maxSize: 244 * 1024 // 244KB
}
}
}
}
七、错误监控系统
1. 全局错误捕获
// utils/errorHandler.js
export function setupErrorHandler(Vue) {
Vue.config.errorHandler = (err, vm, info) => {
console.error(`Error in ${info}:`, err)
trackError({
type: 'vue_error',
message: err.message,
component: vm.$options.name,
stack: err.stack,
info
})
}
window.addEventListener('unhandledrejection', event => {
trackError({
type: 'promise_error',
reason: event.reason
})
})
}
function trackError(errorInfo) {
axios.post('/api/errors', errorInfo).catch(() => {})
}
2. 性能监控
// utils/performance.js
export function trackPerformance() {
if ('PerformanceObserver' in window) {
const observer = new PerformanceObserver((list) => {
const entries = list.getEntries()
entries.forEach(entry => {
if (entry.entryType === 'navigation') {
sendTiming({
dns: entry.domainLookupEnd - entry.domainLookupStart,
tcp: entry.connectEnd - entry.connectStart,
ttfb: entry.responseStart - entry.requestStart,
load: entry.loadEventEnd - entry.loadEventStart
})
}
})
})
observer.observe({ entryTypes: ['navigation', 'resource'] })
}
function sendTiming(timing) {
navigator.sendBeacon('/api/performance', timing)
}
}
八、总结与扩展
通过本教程,您已经掌握了:
- 高并发秒杀系统实现
- 多端适配解决方案
- 支付系统集成方案
- 前端性能优化策略
- 错误监控系统搭建
扩展学习方向:
- Web Workers处理复杂计算
- SSR服务端渲染优化
- PWA离线应用开发
- 微前端架构改造