使用Taro 实现的小程序商城的购物车功能模块
程序员文章站
2024-03-25 21:49:34
...
Taro 是一套遵循 React 语法规范的 多端开发 解决方案。
现如今市面上端的形态多种多样,Web、React-Native、微信小程序等各种端大行其道,当业务要求同时在不同的端都要求有所表现的时候,针对不同的端去编写多套代码的成本显然非常高,这时候只编写一套代码就能够适配到多端的能力就显得极为需要。
使用 Taro,我们可以只书写一套代码,再通过 Taro 的编译工具,将源代码分别编译出可以在不同端(微信/百度/支付宝/字节跳动/QQ/京东小程序、快应用、H5、React-Native 等)运行的代码。
官方文档:https://nervjs.github.io/taro/
项目已上传GitHub:https://github.com/LazyTraveller/Jerry-Taro-Demo/blob/master/README.md
一、使用Taro cli工具初始化项目
1. 安装taro脚手架工具
首先,你需要使用 npm 或者 yarn 全局安装@tarojs/cli,或者直接使用npx:
# 使用 npm 安装 CLI
$ npm install -g @tarojs/cli
# OR 使用 yarn 安装 CLI
$ yarn global add @tarojs/cli
# OR 安装了 cnpm,使用 cnpm 安装 CLI
$ cnpm install -g @tarojs/cli
2. 初始化taro项目
使用命令创建模板项目
$ taro init myApp
npm 5.2+ 也可在不全局安装的情况下使用 npx 创建模板项目
$ npx @tarojs/cli init myApp
3. 进入myApp目录,安装依赖
# 使用 yarn 安装依赖
$ yarn
# OR 使用 cnpm 安装依赖
$ cnpm install
# OR 使用 npm 安装依赖
$ npm install
4. 编译项目,开启Dev模式,生成小程序 -- dist目录
# yarn
$ yarn dev:weapp
$ yarn build:weapp
# npm script
$ npm run dev:weapp
$ npm run build:weapp
# 仅限全局安装
$ taro build --type weapp --watch
$ taro build --type weapp
# npx 用户也可以使用
$ npx taro build --type weapp --watch
$ npx taro build --type weapp
5. 使用微信开发者工具,打开项目中的dist目录
二、小程序购物车功能的实现过程
效果图:
三、具体实现代码
src/pages/cart/cart.js
import { View, Icon, Navigator, Image, Text, } from '@tarojs/components'
import Taro from '@tarojs/taro'
import './cart.less'
class Cart extends Taro.Component {
config = {
navigationBarTitleText: '购物车'
}
state = {
carts: [
{
id: 1,
title: '好喝⾼颜值MEOW莫斯卡托⽓泡葡萄酒甜型⾹槟少⼥粉猫起泡酒(v1)',
image:
'https://tva1.sinaimg.cn/large/00831rSTgy1gczok56tkzj30m80m8qe4.jpg',
num: 3,
price: '88.00',
selected: true
},
{
id: 2,
title: '好喝⾼颜值MEOW莫斯卡托⽓泡葡萄酒甜型⾹槟少⼥粉猫起泡酒(v2)',
image:
'https://tva1.sinaimg.cn/large/00831rSTgy1gczok56tkzj30m80m8qe4.jpg',
num: 1,
price: '188.00',
selected: true
},
{
id: 3,
title: '好喝⾼颜值MEOW莫斯卡托⽓泡葡萄酒甜型⾹槟少⼥粉猫起泡酒(v3)',
image:
'https://tva1.sinaimg.cn/large/00831rSTgy1gczok56tkzj30m80m8qe4.jpg',
num: 2,
price: '288.00',
selected: false
},
{
id: 4,
title: '好喝⾼颜值MEOW莫斯卡托⽓泡葡萄酒甜型⾹槟少⼥粉猫起泡酒(v4)',
image:
'https://tva1.sinaimg.cn/large/00831rSTgy1gczok56tkzj30m80m8qe4.jpg',
num: 2,
price: '388.00',
selected: false
}
], // 购物车列表
hascheckList: [],
totalPrice: 0, // 总价,初始为0
selectAllStatus: true // 全选状态,默认全选
}
componentDidShow() {
const cart = [
]
this.setState({
carts: cart
})
this.getTotalPrice();
}
/**
* 计算总价
*/
getTotalPrice() {
let carts = this.state.carts // 获取购物车列表
let total = 0
for (let i = 0; i < carts.length; i++) {
// 循环列表得到每个数据
if (carts[i].selected) {
// 判断选中才会计算价格
total += carts[i].num * carts[i].price // 所有价格加起来
}
}
this.setState({
// 最后赋值到data中渲染到页面
carts: carts,
totalPrice: total.toFixed(2)
})
}
/**
* 绑定加数量事件
*/
addCount(e) {
const index = e.currentTarget.dataset.index
let carts = this.state.carts
let num = carts[index].num
num = num + 1
carts[index].num = num
this.setState({
carts: carts
})
this.getTotalPrice()
}
/**
* 绑定减数量事件
*/
minusCount(e) {
const index = e.currentTarget.dataset.index
let carts = this.state.carts
let num = carts[index].num
if (num <= 1) {
return false
}
num = num - 1
carts[index].num = num
this.setState({
carts: carts
})
this.getTotalPrice()
}
/**
* 删除购物车当前商品
*/
deleteList(e) {
const index = e.currentTarget.dataset.index
let carts = this.state.carts
carts.splice(index, 1)
this.setState({
carts: carts
})
if (!carts.length) {
this.setState({
hasList: false
})
} else {
this.getTotalPrice()
}
}
/**
* 当前商品选中事件
*/
selectList(id,e) {
const index = e.currentTarget.dataset.index
let carts = this.state.carts
// const selected = carts[index].selected
// carts[index].selected = !selected
carts.forEach(item => {
if (id == item.id) {
item.selected = !item.selected
}
})
// const checkall = this.data.selectAllStatus === true ? false : false
this.setState({
carts: carts,
// selectAllStatus: false
})
const selectAllStatus = carts.every(item => item.selected)
this.setState({
selectAllStatus: selectAllStatus
})
this.getTotalPrice()
}
/**
* 购物车全选事件
*/
selectAll(e) {
let selectAllStatus = this.state.selectAllStatus
selectAllStatus = !selectAllStatus
let carts = this.state.carts
for (let i = 0; i < carts.length; i++) {
carts[i].selected = selectAllStatus
}
this.setState({
selectAllStatus: selectAllStatus,
carts: carts
})
this.getTotalPrice()
}
// 结算
closeFun() {
let list = []
let listTotal = []
this.state.carts.map((v, k) => {
console.log('购物车数据', v)
if (v.select) {
list.push(v)
} else {
listTotal.push(v)
}
})
}
render() {
const { carts, selectAllStatus, totalPrice, hasList } = this.state;
let count = 0;
carts.map(it => {
if(it.selected === true) {
count++;
}
})
return (
<View className="main">
{carts.length > 0 ? (
<View>
<View className="cart-box">
{carts.map((item, index) => {
return (
<View className="cart-list" key={index}>
{item.selected ? (
<Icon
type="success"
color="#b30000"
data-index={index}
className="cart-pro-select"
onClick={this.selectList.bind(this,item.id)}
></Icon>
) : (
<Icon
type="circle"
className="cart-pro-select"
data-index={index}
onClick={this.selectList.bind(this,item.id)}
></Icon>
)}
<Navigator url={'../details/details?id=' + item.id}>
<Image className="cart-thumb" src={item.image}></Image>
</Navigator>
<Text className="cart-pro-name">{item.title}</Text>
<Text className="cart-pro-price">{'¥' + item.price}</Text>
<View className="cart-count-box">
<Text
className="cart-count-down"
onClick={this.minusCount}
data-index={index}
>
-
</Text>
<Text className="cart-count-num">{item.num}</Text>
<Text
className="cart-count-add"
onClick={this.addCount}
data-index={index}
>
+
</Text>
</View>
<Text
className="cart-del"
onClick={this.deleteList}
data-index={index}
>
删除
</Text>
</View>
)
})}
</View>
<View className="cart-footer">
{selectAllStatus ? (
<Icon
type="success_circle"
color="#b30000"
className="total-select"
onClick={this.selectAll}
></Icon>
) : (
<Icon
type="circle"
color="#b30000"
className="total-select"
onClick={this.selectAll}
></Icon>
)}
<Navigator url="../orders/orders">
<View className="order-icon"></View>
</Navigator>
<Text >{count> 0? `已选(${count})`: '全选'}</Text>
<Text className="cart-toatl-price">{'合计¥' + totalPrice}</Text>
<Text className="pay" onClick={this.closeFun} data-index={index}>
立即下单
</Text>
</View>
</View>
) : (
<View>
<View className="cart-no-data">购物车是空的哦~</View>
</View>
)}
</View>
)
}
}
export default Cart
src/pages/cart/cart.less
/* pages/cart/cart.wxss */
.cart-box{
padding-bottom: 100px;
margin-bottom: 10px
}
.cart-list{
position: relative;
padding: 20px 20px 20px 285px;
height: 185px;
border-bottom: 1px solid #e9e9e9;
}
.cart-list .cart-pro-select{
position: absolute;
left: 20px;
top: 90px;
width: 45px;
height: 45px;
}
.cart-list .cart-thumb{
position: absolute;
top: 20px;
left: 85px;
width: 185px;
height: 185px;
border-radius:5px;
box-shadow:5px 2px 6px #000
}
.cart-list .cart-pro-name{
display: inline-block;
// width: 500px;
height: 105px;
line-height: 50px;
overflow: hidden;
font-family: Microsoft Yahei, Cochin, Georgia, Times, 'Times New Roman', serif;
font-size:28px;
margin-right: 15px
}
.cart-list .cart-pro-price{
display: inline-block;
font-size:30px;
color: #b30000;
height: 105px;
line-height: 50px;
}
.cart-list .cart-count-box{
position: absolute;
left: 420px;
bottom: 20px;
width: 250px;
height: 80px;
}
.cart-list .cart-count-box text{
display: inline-block;
line-height: 80px;
text-align: center;
}
.cart-count-down,.cart-count-add{
font-size: 32px;
width: 60px;
height: 80px;
font-family: Microsoft Yahei, Cochin, Georgia, Times, 'Times New Roman', serif;
border: silver solid 1px;
border-radius: 10px;
}
.cart-count-num{
width: 80px;
font-size: 32px;
height: 80px;
border-radius: 10px;
border: silver solid 1px;
margin-left: 1px;
margin-right: 1px;
}
.cart-del{
position: absolute;
right: 15px;
bottom: 20px;
width: 80px;
height: 80px;
line-height: 80px;
text-align: center;
font-family: Arial,Helvetica,sans-serif;
font-size:30px;
color: #b30000;
text-shadow: black;
}
.cart-footer{
position: fixed;
bottom: 0;
left: 0;
width: 100%;
height: 90px;
line-height: 90px;
padding:0 100px 0 80px;
box-sizing: border-box;
background: #bfbfbf;
color: #4d4d4d;
font-family: Microsoft Yahei, Cochin, Georgia, Times, 'Times New Roman', serif;
font-size: 30px;
}
.total-select{
position: absolute;
left: 20px;
top: 25px;
width: 45px;
height: 45px;
}
.order-icon{
position: absolute;
right: 40px;
top: 25px;
width: 45px;
height: 45px;
background-size: 100%;
}
.cart-toatl-price{
/* float: right; */
margin-left:80px;
text-align: center;
width: 100px;
font-family: Microsoft Yahei, Cochin, Georgia, Times, 'Times New Roman', serif;
color: #b30000;
font-size: 30px;
}
.pay {
position: absolute;
right: 0;
background-color: #b30000;
height: 100%;
width: 200px;
text-align: center;
font-family: Microsoft Yahei, Cochin, Georgia, Times, 'Times New Roman', serif;
font-size: 26px;
color: #f2f2f2;
text-align: center
}
.cart-no-data{
padding:40px 0;
color: #999;
text-align: center;
}
注意:检查本地电脑taro的版本,电脑需要和项目的taro版本号相同,否则发送编译错误,该项目的taro CLI版本为v2.1.1
官方提供的两个解决方案:
1、 对电脑的taro进行升级
# taro
$ taro update self [version]
# npm
npm i -g @tarojs/aaa@qq.com[version]
# yarn
yarn global add @tarojs/aaa@qq.com[version]
2、 对项目的taro进行升级
$ taro update project [version]
version 为选填,如:1.x.x/latest 等,将会直接更新到指定版本