好的,下面帮你把之前的完整页面拆分成标准的 Vue 单文件组件格式(基于 Vue 2 + Element UI),你可以直接放到 src/views/spmSys/ol/index.vue 文件中使用。
注意:
- 全局引入 Element UI(JS + CSS)请在你的项目入口文件
main.js 里完成:
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
-
任何全局 CSS reset 建议放你项目的全局样式中,不建议写在单文件组件内。
-
这个组件内的样式已做适当调整,只保留必要样式。
src/views/spmSys/ol/index.vue
<template>
<div class="app-container">
<!-- 顶部工具栏和搜索表单 -->
<div class="top-bar">
<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<el-form-item label="商品名称" prop="commName">
<el-input v-model="queryParams.commName" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery" />
</el-form-item>
<el-form-item label="商品类型" prop="classId">
<el-select v-model="queryParams.classId" placeholder="请选择商品类型" clearable>
<el-option
v-for="item in classOptions"
:key="item.classId"
:label="item.className"
:value="item.classId"
/>
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
</el-form-item>
</el-form>
<div class="cart-button-container">
<el-button type="primary" icon="el-icon-shopping-cart" @click="cartVisible = true">
购物车 <el-badge :value="cartItems.length" class="ml-2" :hidden="cartItems.length === 0" />
</el-button>
</div>
</div>
<!-- 商品卡片展示区域 -->
<div v-if="loading" style="text-align: center; padding: 50px 0;">
<i class="el-icon-loading" style="font-size: 32px; margin-bottom: 20px;"></i>
<p>加载商品中...</p>
</div>
<div v-else>
<!-- 当没有商品时显示 -->
<div v-if="displayedCommList.length === 0" class="empty-cart">
<i class="el-icon-goods text-gray-400 text-5xl mb-4"></i>
<p class="text-gray-500">没有找到符合条件的商品</p>
<el-button type="primary" size="small" @click="resetQuery">重置筛选条件</el-button>
</div>
<!-- 商品卡片容器 -->
<div v-else class="cards-container">
<div v-for="product in displayedCommList" :key="product.commId" class="card-item">
<div class="card-header">
<img v-if="product.commImage" :src="product.commImage" class="card-image" alt="商品图片" />
<div v-else class="card-image image-placeholder">
<i class="el-icon-picture"></i>
<span>暂无图片</span>
</div>
<div class="card-category">{{ getClassName(product.classId) }}</div>
<div class="stock-status" :class="{'no-stock': product.inv <= 0}">
{{ product.inv <= 0 ? '已售罄' : `库存: ${product.inv}件` }}
</div>
</div>
<div class="card-body">
<h3 class="card-title">{{ product.commName }}</h3>
<p class="card-spec">规格: {{ product.unit || '暂无规格信息' }}</p>
<div class="card-price">¥{{ formatPrice(product.price) }}</div>
<div class="production-info">
<span>生产: {{ parseTime(product.pd, '{y}-{m}-{d}') }}</span>
<span>保质期: {{ product.exp }}天</span>
</div>
</div>
<div class="card-footer">
<el-button
type="primary"
icon="el-icon-shopping-cart"
class="add-to-cart-btn"
@click="addToCart(product)"
:disabled="product.inv <= 0"
>
{{ product.inv <= 0 ? '无库存' : '加入购物车' }}
</el-button>
</div>
</div>
</div>
</div>
<!-- 分页 -->
<div v-show="displayedCommList.length > 0" class="pagination-container">
<el-pagination
background
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="queryParams.pageNum"
:page-sizes="[12, 24, 48, 96]"
:page-size="queryParams.pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="filteredCommList.length">
</el-pagination>
</div>
<!-- 购物车侧边栏 -->
<el-drawer
title="购物车"
:visible.sync="cartVisible"
direction="rtl"
size="40%"
@close="onCartClose"
class="cart-drawer"
>
<div v-if="cartItems.length === 0" class="empty-cart">
<i class="el-icon-shopping-cart-2 text-gray-400 text-5xl mb-4"></i>
<p class="text-gray-500">购物车是空的</p>
<el-button type="primary" size="small" @click="cartVisible = false">继续购物</el-button>
</div>
<div v-else style="padding-bottom: 120px;">
<el-scrollbar style="height: calc(100vh - 200px);">
<div class="cart-items-container">
<div class="cart-item" v-for="item in cartItems" :key="item.commId">
<div class="item-content">
<img v-if="item.commImage" :src="item.commImage" class="item-image" alt="购物车商品图片" />
<div v-else style="background: #f5f7fa; width: 80px; height: 80px; display: flex; align-items: center; justify-content: center;">
<i class="el-icon-picture"></i>
</div>
<div class="item-details">
<h3 class="item-name">{{ item.commName || '未知商品' }}</h3>
<p class="item-spec">{{ item.unit || '-' }}</p>
<div class="item-price-info">
<p class="item-price">¥{{ formatPrice(item.price || 0) }}</p>
<p class="item-subtotal">小计: ¥{{ formatPrice(item.price * item.quantity) }}</p>
</div>
<p v-if="item.inv < item.quantity" class="stock-warning">
<i class="el-icon-warning"></i> 库存不足 (仅剩 {{ item.inv }} 件)
</p>
</div>
</div>
<div class="item-actions">
<div class="quantity-control">
<el-button
size="mini"
class="quantity-btn"
@click="decreaseQuantity(item)"
:disabled="item.quantity <= 1"
>
<i class="el-icon-minus"></i>
</el-button>
<el-input
v-model.number="item.quantity"
type="number"
size="mini"
:min="1"
:max="item.inv"
:disabled="item.inv <= 0"
class="quantity-input"
@change="updateCartItem(item)"
/>
<el-button
size="mini"
class="quantity-btn"
@click="increaseQuantity(item)"
:disabled="item.quantity >= item.inv"
>
<i class="el-icon-plus"></i>
</el-button>
</div>
<el-button
size="mini"
type="danger"
class="remove-btn"
@click="removeFromCart(item)"
>
<i class="el-icon-delete"></i> 移除
</el-button>
</div>
</div>
</div>
</el-scrollbar>
<!-- 结算区域 -->
<div class="checkout-section">
<div class="checkout-info">
<div class="info-row">
<span class="info-label">商品数量:</span>
<span class="info-value">{{ getTotalQuantity() }}件</span>
</div>
<div class="info-row">
<span class="info-label">订单总价:</span>
<span class="info-value total-price">¥{{ formatPrice(calculateTotal()) }}</span>
</div>
</div>
<el-button
type="primary"
size="large"
:disabled="cartItems.length === 0"
@click="checkout"
class="checkout-btn"
>
结算
</el-button>
</div>
</div>
</el-drawer>
<!-- 结算对话框 -->
<el-dialog :title="'确认订单 #' + orderId" :visible.sync="checkoutVisible" width="500px" append-to-body>
<el-form :model="checkoutForm" label-width="100px">
<el-form-item label="商品数量">
<span>{{ getTotalQuantity() }}件</span>
</el-form-item>
<el-form-item label="订单总价">
<span class="text-primary font-bold">¥{{ formatPrice(calculateTotal()) }}</span>
</el-form-item>
<el-form-item label="支付方式">
<el-radio-group v-model="checkoutForm.paymentMethod">
<el-radio label="online">线上支付</el-radio>
<el-radio label="offline">线下自提</el-radio>
</el-radio-group>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="checkoutVisible = false">取消</el-button>
<el-button type="primary" @click="submitOrder">确认支付</el-button>
</div>
</el-dialog>
<!-- 二维码支付弹窗 -->
<el-dialog
title="扫码支付"
:visible.sync="qrCodeVisible"
width="350px"
center
append-to-body
:close-on-click-modal="false"
:close-on-press-escape="false"
:show-close="false"
>
<div class="qr-code-container">
<p class="text-center mb-4">请使用手机扫描下方二维码完成支付</p>
<div class="qr-code-wrapper">
<img src="https://via.placeholder.com/200/cccccc?text=支付二维码" alt="支付二维码" class="qr-code-image" />
</div>
<p class="text-center text-gray-500 mt-4">订单号: {{ orderId }}</p>
<p class="text-center text-xl font-bold mt-2">¥{{ formatPrice(calculateTotal()) }}</p>
</div>
<div slot="footer" class="dialog-footer flex justify-center">
<el-button type="success" size="medium" @click="handlePaymentSuccess">
<i class="el-icon-success"></i> 我已支付
</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
export default {
name: 'Index',
data() {
return {
loading: true,
showSearch: true,
total: 0,
commList: [], // 所有商品数据
filteredCommList: [], // 筛选后
displayedCommList: [], // 分页后
queryParams: {
pageNum: 1,
pageSize: 12,
commName: null,
classId: null,
},
classOptions: [
{ classId: 1, className: "水果类" },
{ classId: 2, className: "蔬菜类" },
{ classId: 3, className: "肉类" },
{ classId: 4, className: "乳制品" },
{ classId: 5, className: "饮料" },
{ classId: 6, className: "零食" }
],
classMap: {
1: "水果类",
2: "蔬菜类",
3: "肉类",
4: "乳制品",
5: "饮料",
6: "零食"
},
cartVisible: false,
cartItems: [],
checkoutVisible: false,
checkoutForm: {
paymentMethod: 'online'
},
orderId: Math.floor(Math.random() * 1000000),
qrCodeVisible: false
}
},
created() {
this.getList()
},
methods: {
/** 模拟加载商品列表 */
getList() {
this.loading = true
setTimeout(() => {
const products = []
const names = [
"富士苹果", "海南香蕉", "新疆香梨", "金枕榴莲", "芒果", "山竹",
"红心火龙果", "巨峰葡萄", "草莓", "木瓜", "大白菜", "生菜",
"西兰花", "胡萝卜", "黄瓜", "西红柿", "茄子", "青椒",
"三文鱼", "牛排", "鸡胸肉", "大虾", "羊排", "培根",
"纯牛奶", "酸奶", "芝士片", "黄油", "冰淇淋", "鸡蛋",
"果汁", "可乐", "矿泉水", "啤酒", "咖啡", "苏打水",
"薯片", "巧克力", "饼干", "坚果", "糖果", "即食面"
]
const units = [
"500g/盒", "1kg/袋", "200g/包", "300g/袋", "1个", "6个装",
"800g/箱", "1.5kg/盒", "250g/盒", "1份", "1把"
]
for (let i = 1; i <= 48; i++) {
const randomStock = Math.floor(Math.random() * 50) + 1
const randomClassId = Math.floor(Math.random() * 6) + 1
const randomDays = Math.floor(Math.random() * 365) + 30
products.push({
commId: i,
commName: names[i % names.length] + (i > names.length ? " " + (Math.floor(i/names.length) + 1) : ""),
commImage: i % 4 === 0 ? "" : `https://picsum.photos/200/200?random=${i}`,
unit: units[Math.floor(Math.random() * units.length)],
price: (Math.random() * 100 + 1).toFixed(2),
inv: i % 8 === 0 ? 0 : randomStock,
pd: new Date(Date.now() - Math.random() * 1000 * 3600 * 24 * 30),
exp: randomDays,
classId: randomClassId
})
}
this.commList = products
this.updateFilteredList()
this.loading = false
}, 800);
},
/** 更新筛选后的列表 */
updateFilteredList() {
this.filteredCommList = this.commList.filter(item => {
const nameMatch = !this.queryParams.commName ||
item.commName.toLowerCase().includes(this.queryParams.commName.toLowerCase());
const classMatch = this.queryParams.classId === null ||
item.classId === this.queryParams.classId;
return nameMatch && classMatch;
});
this.updateDisplayedList()
},
/** 更新分页后的列表 */
updateDisplayedList() {
const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize
const end = start + this.queryParams.pageSize
this.displayedCommList = this.filteredCommList.slice(start, end)
},
/** 获取商品类型名称 */
getClassName(classId) {
return this.classMap[classId] || `未知类型(${classId})`
},
/** 格式化价格显示 */
formatPrice(price) {
return Number(price).toFixed(2)
},
/** 搜索按钮操作 */
handleQuery() {
this.queryParams.pageNum = 1
this.updateFilteredList()
},
/** 重置按钮操作 */
resetQuery() {
this.queryParams.commName = null
this.queryParams.classId = null
this.queryParams.pageNum = 1
this.updateFilteredList()
},
/** 分页大小变化 */
handleSizeChange(newSize) {
this.queryParams.pageSize = newSize
this.updateDisplayedList()
},
/** 当前页变化 */
handleCurrentChange(newPage) {
this.queryParams.pageNum = newPage
this.updateDisplayedList()
},
/** 加入购物车逻辑 */
addToCart(product) {
if (!product || !product.commId) {
this.$message.error("商品信息不完整")
return
}
if (product.inv <= 0) {
this.$message.warning("商品库存不足")
return
}
const existingItem = this.cartItems.find(item => item.commId === product.commId)
if (existingItem) {
if (existingItem.quantity < existingItem.inv) {
existingItem.quantity += 1
this.$message.success(`已增加 ${product.commName} 的数量`)
} else {
this.$message.warning(`已达到最大库存数量`)
}
} else {
const cartItem = {
commId: product.commId,
commName: product.commName || '未知商品',
commImage: product.commImage,
unit: product.unit || '-',
price: product.price || 0,
inv: product.inv || 0,
pd: product.pd,
exp: product.exp,
classId: product.classId,
quantity: 1
}
this.cartItems.push(cartItem)
this.$message.success(`已将 ${product.commName} 加入购物车`)
}
},
/** 减少购物车商品数量 */
decreaseQuantity(item) {
if (item.quantity > 1) {
item.quantity -= 1
}
},
/** 增加购物车商品数量 */
increaseQuantity(item) {
if (item.quantity < item.inv) {
item.quantity += 1
} else {
this.$message.warning(`已达到最大库存数量`)
}
},
/** 更新购物车商品 */
updateCartItem(item) {
if (isNaN(item.quantity)) {
item.quantity = 1
} else if (item.quantity < 1) {
item.quantity = 1
} else if (item.inv && item.quantity > item.inv) {
item.quantity = item.inv
this.$message.warning(`已调整为最大库存数量`)
}
},
/** 从购物车移除商品 */
removeFromCart(item) {
const index = this.cartItems.findIndex(i => i.commId === item.commId)
if (index !== -1) {
this.cartItems.splice(index, 1)
this.$message.success(`已从购物车移除 ${item.commName}`)
if (this.cartItems.length === 0) {
this.cartVisible = false
}
}
},
/** 计算购物车总价 */
calculateTotal() {
return this.cartItems.reduce((total, item) => total + (item.price * item.quantity), 0)
},
/** 获取购物车商品总数量 */
getTotalQuantity() {
return this.cartItems.reduce((total, item) => total + item.quantity, 0)
},
/** 购物车关闭时的回调 */
onCartClose() {
// 可添加清理逻辑
},
/** 打开结算页面 */
checkout() {
const insufficientStockItems = this.cartItems.filter(item => item.quantity > item.inv)
if (insufficientStockItems.length > 0) {
const names = insufficientStockItems.map(item => item.commName).join(', ')
this.$message.warning(`以下商品库存不足:${names}`)
return
}
this.checkoutVisible = true
this.orderId = Math.floor(Math.random() * 1000000)
},
/** 提交订单 */
async submitOrder() {
try {
const loadingInstance = this.$loading({
lock: true,
text: '正在处理订单...',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.1)'
})
await new Promise(resolve => setTimeout(resolve, 1000))
this.orderId = Date.now() + Math.floor(Math.random() * 1000)
this.checkoutVisible = false
if (this.checkoutForm.paymentMethod === 'online') {
this.qrCodeVisible = true
} else {
this.handlePaymentSuccess()
}
loadingInstance.close()
} catch (error) {
console.error('订单提交失败:', error)
this.$message.error(`订单提交失败: ${error.message || '请重试'}`)
this.$loading().close()
}
},
/** 处理支付成功 */
handlePaymentSuccess() {
this.cartItems.forEach(cartItem => {
const product = this.commList.find(p => p.commId === cartItem.commId)
if (product && product.inv >= cartItem.quantity) {
product.inv -= cartItem.quantity
}
})
this.cartItems = []
this.qrCodeVisible = false
this.cartVisible = false
this.$message({
message: `支付成功!订单号:${this.orderId}`,
type: 'success',
duration: 3000
})
this.updateFilteredList()
},
/** 时间格式化方法 */
parseTime(time, pattern) {
if (!time) return ""
const date = new Date(time)
if (isNaN(date.getTime())) return ""
const format = pattern || '{y}-{m}-{d}'
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
}
return format.replace(/{(y|m|d)+}/g, (result, key) => {
let value = formatObj[key]
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
}
}
}
</script>
<style scoped>
/* 部分核心样式,从你原始 CSS 中保留并简化 */
.app-container {
max-width: 1600px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}
/* 顶部工具栏 */
.top-bar {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
flex-wrap: wrap;
gap: 15px;
padding-bottom: 15px;
border-bottom: 1px solid #ebeef5;
}
.el-form--inline .el-form-item {
margin-right: 10px;
margin-bottom: 15px;
}
.cart-button-container {
margin-left: auto;
}
.ml-2 {
margin-left: 8px;
}
/* 卡片容器 */
.cards-container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
gap: 25px;
padding: 10px 0;
margin-top: 20px;
}
.card-item {
background-color: #fff;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.06);
transition: all 0.3s ease;
overflow: hidden;
display: flex;
flex-direction: column;
height: 100%;
position: relative;
}
.card-item:hover {
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
transform: translateY(-5px);
}
.card-header {
position: relative;
}
.card-image {
width: 100%;
height: 180px;
object-fit: cover;
display: block;
}
.image-placeholder {
display: flex;
align-items: center;
justify-content: center;
background-color: #f5f7fa;
color: #909399;
font-size: 14px;
height: 180px;
}
.card-category {
position: absolute;
top: 10px;
right: 10px;
background-color: rgba(64, 158, 255, 0.85);
color: white;
padding: 3px 8px;
border-radius: 10px;
font-size: 12px;
}
.stock-status {
position: absolute;
bottom: 50px;
left: 0;
right: 0;
padding: 6px;
background-color: rgba(0, 0, 0, 0.5);
color: white;
text-align: center;
font-size: 13px;
}
.no-stock {
background-color: rgba(245, 108, 108, 0.7);
}
.card-body {
padding: 15px;
flex: 1;
display: flex;
flex-direction: column;
}
.card-title {
font-size: 16px;
font-weight: 600;
margin-bottom: 8px;
color: #303133;
line-height: 1.4;
}
.card-spec {
font-size: 13px;
color: #606266;
margin-bottom: 8px;
}
.card-price {
color: #f56c6c;
font-weight: 700;
font-size: 18px;
margin: 8px 0;
}
.production-info {
display: flex;
justify-content: space-between;
font-size: 12px;
color: #909399;
padding-top: 8px;
border-top: 1px dashed #ebeef5;
margin-top: auto;
}
.card-footer {
padding: 10px 15px;
display: flex;
justify-content: center;
background-color: #fafafa;
}
.add-to-cart-btn {
width: 100%;
}
/* ...剩余样式你可根据需要自行添加 */
/* 响应式调整 */
@media (max-width: 768px) {
.top-bar {
flex-direction: column;
align-items: stretch;
}
.cart-button-container {
margin-left: 0;
align-self: center;
margin-top: 10px;
}
.cards-container {
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
}
}
@media (max-width: 480px) {
.cards-container {
grid-template-columns: 1fr;
}
.app-container {
padding: 15px;
}
}
/* 购物车抽屉及其他自定义样式,请根据需要补充 */
</style>
使用说明
- 引入Element UI 请确认你项目入口文件
main.js 里引入了 element-ui 及样式,并执行了 Vue.use(ElementUI)。
- 路由配置 该组件按你项目路由配置引入即可。
- 自定义样式 你可以根据项目规范调整样式作用域(比如取消
scoped),或拆出公共样式文件。
- 图片和接口数据 这里商品数据是模拟生成的,真实项目替换接口即可。
如果你需要我帮你做项目入口配置或多组件拆分,也可以告诉我。祝你开发顺利!