vue用element实现购物
使用 Vue 和 Element UI 实现购物功能
安装依赖
确保项目中已安装 Vue 和 Element UI。若未安装,可通过以下命令安装:
npm install element-ui
引入 Element UI
在 main.js 中全局引入 Element UI:
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
创建购物车组件
在 Vue 组件中实现购物车功能,包含商品列表、添加商品和结算逻辑。
商品列表展示
使用 el-table 展示商品列表,支持选择商品和调整数量:
<template>
<div>
<el-table :data="products" border>
<el-table-column prop="name" label="商品名称"></el-table-column>
<el-table-column prop="price" label="价格"></el-table-column>
<el-table-column label="数量">
<template slot-scope="scope">
<el-input-number v-model="scope.row.quantity" :min="1"></el-input-number>
</template>
</el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button type="danger" @click="removeProduct(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
</div>
</template>
添加商品逻辑
通过 el-dialog 实现添加商品的弹窗:
<el-button type="primary" @click="dialogVisible = true">添加商品</el-button>
<el-dialog title="添加商品" :visible.sync="dialogVisible">
<el-form :model="newProduct">
<el-form-item label="商品名称">
<el-input v-model="newProduct.name"></el-input>
</el-form-item>
<el-form-item label="价格">
<el-input v-model="newProduct.price" type="number"></el-input>
</el-form-item>
</el-form>
<span slot="footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="addProduct">确认</el-button>
</span>
</el-dialog>
结算功能
计算总价并提供结算按钮:
<div class="total">
<span>总价: {{ totalPrice }}</span>
<el-button type="success" @click="checkout">结算</el-button>
</div>
数据与逻辑实现
在 script 部分定义数据和方法:
export default {
data() {
return {
products: [
{ name: '商品1', price: 100, quantity: 1 },
{ name: '商品2', price: 200, quantity: 1 }
],
newProduct: { name: '', price: 0, quantity: 1 },
dialogVisible: false
};
},
computed: {
totalPrice() {
return this.products.reduce((sum, item) => sum + item.price * item.quantity, 0);
}
},
methods: {
addProduct() {
this.products.push({ ...this.newProduct });
this.dialogVisible = false;
this.newProduct = { name: '', price: 0, quantity: 1 };
},
removeProduct(product) {
this.products = this.products.filter(p => p !== product);
},
checkout() {
this.$message.success(`结算成功,总价: ${this.totalPrice}`);
}
}
};
样式优化
通过 CSS 美化购物车界面:
.total {
margin-top: 20px;
text-align: right;
font-size: 18px;
}
功能扩展
- 本地存储:使用
localStorage持久化购物车数据。 - 接口集成:通过 API 获取商品列表和提交订单。
- 用户验证:结合后端实现用户登录和订单管理。







