本文章写的是访问后台接口的简单封装,能够更快的修改接口和URL地址:本文涉及到四个文件,这四个文件我都放在一个取名叫api的文件夹里面,我们可以假设这四个文件名字为:request.js、requestUrl.js、index.js和index.vue这四个文件,接下来简单说说这四个文件的内容:
import url from "@/api/requestUrl.js"
const request = (config) => {
// 处理 apiUrl
config.url = url.requestUrl + config.url;
if(!config.data) config.data = {};
config.timeout = 300000;
let promise = new Promise(function(resolve, reject) {
uni.request(config).then(responses => {
// 异常
if (responses[0]) {
reject({message : "网络超时"});
} else {
let response = responses[1].data; // 如果返回的结果是data.data的,嫌麻烦可以用这个,return res,这样只返回一个data
resolve(response);
}
}).catch(error => {
reject(error);
})
})
return promise;
};
export default request;
export default {
// requestUrl: 'https://www.baidu.com'
requestUrl: 'http://192.168.1.1:3000'
};
import request from '@/api/request'; // 引入封装好的request
// 查询购物车信息
function getCart(data) {
return request({
url: '/userProduct',
method: 'GET',
data: data
})
}
// 加入购物车
function addCart(data) {
return request({
url: '/userProduct',
method: 'POST',
data: data
})
}
// 修改购物车信息
function modifyCart(data){
return request({
url:'/userProduct',
method: 'PUT',
data: data
})
}
// 移除购物车
function deleteCart(data, data2){
return request({
url:`/userProduct/${data}/${data2}`,
method: 'DELETE'
})
}
export default{
getCart,
addCart,
modifyCart,
deleteCart
}
<template>
<view>
<view style="height: calc(100% - 84rpx);padding: 20rpx;background-color: #fff">
<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" @scrolltoupper="upper"
@scrolltolower="lower" @scroll="scroll" style="height: 100%;">
<view class="cu-list menu-avatar">
<view class="cu-item" :class="modalName=='move-box-'+ index?'move-cur':''"
v-for="(item,index) in cartList" :key="index" @touchstart="ListTouchStart"
@touchmove="ListTouchMove" @touchend="ListTouchEnd" :data-target="'move-box-' + index">
<view>
<checkbox-group @change="singleSelect(item)">
<checkbox class='choose-state round red' :checked="item.isChecked"></checkbox>
</checkbox-group>
<!-- <evan-checkbox class="choose-state" v-model="item.isChecked" @change="singleSelect(item)"></evan-checkbox> -->
</view>
<view class="image-avatar cu-avatar radius xl"
:style="[{backgroundImage:'url(https://ossweb-img.qq.com/images/lol/web201310/skin/big21005.jpg)'}]">
</view>
<view class="image-content content flex-sub">
<view class="text-grey">{{item.productName}}</view>
<view class="text-red flex justify-between">
<text class="image-price text-price text-xl">{{item.productPrice}}</text>
<view class="reduce-add">
<!-- <view class="reduce-btn" @click="reduce">-</view> -->
<image class="image-style reduce-btn" src="../../static/reduce.png"
@click="reduce(item)">
</image>
<view class="count-val text-xl">
<!-- <input type="number" v-model="countModel" :value="item.count" @input="countVal" /> -->
<text>{{item.count}}</text>
</view>
<!-- <view class="add-btn" @click="add">+</view> -->
<image class="image-style add-btn" src="../../static/add.png" @click="add(item)">
</image>
</view>
</view>
</view>
<view class="move">
<view class="bg-red" @click="deleteCart(item)">删除</view>
</view>
</view>
</view>
<!-- <view class="loading">{{loadingText}}</view> -->
</scroll-view>
</view>
<view class="go-settlement cu-bar bg-white tabbar border shop">
<view class="all-choose">
<checkbox-group @change="selectAll()">
<checkbox class='choose-state round red' :checked="allChecked">全选</checkbox>
</checkbox-group>
<!-- <evan-checkbox class="choose-state" v-model="isAllChecked" @change="selectAll()">全选</evan-checkbox> -->
</view>
<view class="total-price">
合计:<text class="text-red">¥{{totalPrice}}</text>
</view>
<view class="to-settle bg-red submit" @tap="showModal" data-target="DialogModal1">去结算({{checkedNum.length}})
</view>
</view>
<view class="cu-modal" :class="modalName=='DialogModal1'?'show':''">
<view class="cu-dialog">
<view class="cu-bar bg-white justify-end">
<view class="content">结算</view>
<view class="action" @tap="hideModal">
<text class="cuIcon-close text-red"></text>
</view>
</view>
<view class="jie-suan padding-xl">
<view class="text-xl" style="padding-bottom: 20rpx;">
结算价格:
<text class="text-red">{{totalPrice}}</text>
</view>
<view style="display: flex;align-items: center;" class="text-black text-xl">
手机号码:
<input type="number" placeholder="请输入手机号码" :value="iptValue" @input="iptChange" />
</view>
</view>
<view class="cu-bar bg-white justify-end">
<view class="action">
<button class="cu-btn line-green text-green" @tap="hideModal">取消</button>
<button class="cu-btn bg-green margin-left" @tap="confirmModal">确定</button>
</view>
</view>
</view>
</view>
</view>
</template>
<script>
import cartApi from '@/api/shoppingCart/index.js'
import orderApi from '@/api/pendingPayment/index.js'
export default {
data() {
return {
isCard: false,
cartList: [],
allChecked: false,
scrollTop: 0,
old: {
scrollTop: 0
},
pH: 0, // 窗口高度
navHeight: 0, // 元素所需高度
loadingText: '加载中。。。',
openid: '',
// 每页条数
size: 30,
// 当前页码
page: 1,
timer: null,
listTouchStart: 0,
listTouchDirection: null,
modalName: null,
userInfo: '',
// 弹窗
modalName: null,
// 手机号码
iptValue: '',
/* 总价格 */
totalPrice: 0,
// 选中个数
checkedNum: []
};
},
computed: {
// 购物车商品总价
// totalPrice() {
// let totalPrice = 0
// console.log("传入的数组是", this.cartList);
// this.cartList.map(item => {
// console.log("888888", item.isChecked);
// // item.isChecked ? totalPrice += item.count * item.productPrice : totalPrice += 0
// if(item.isChecked){
// var sum = item.count * item.productPrice;
// totalPrice = totalPrice + sum;
// }else{
// totalPrice = totalPrice + 0
// }
// })
// return totalPrice;
// }
},
// 页面刚刚加载
onLoad() {
this.openid = uni.getStorageSync("openid");
this.userInfo = uni.getStorageSync("hsdhak");
console.log("获取到的openid是", this.openid);
// this.getCartList();
},
// 触底加载
// onReachBottom() {
// let that = this;
// uni.showNavigationBarLoading();
// if (that.timer != null) {
// clearTimeout(that.timer);
// }
// that.timer = setTimeout(function() {
// console.log("下拉加载更多购物车");
// that.page++;
// that.getCartList();
// uni.hideNavigationBarLoading();
// }, 2000);
// },
onShow() {
this.getCartList();
this.totalPrice = 0;
this.checkedNum.length = 0;
},
onReady() {
let that = this;
uni.getSystemInfo({ //调用uniapp窗口获取屏幕高度
success(res) { // 成功回调函数
console.log("购物车回调函数", res);
that.pH = res.windowHeight // windowHeight为窗口高度,主要使用的是这个
let titleH = uni.createSelectorQuery().select(".scroll-Y"); // 想要获取高度的元素名 (class / id)
titleH.boundingClientRect(data => {
console.log("距离底部的距离的数据", data);
let pH = that.pH;
that.navHeight = pH - data.bottom //计算高度:元素高度=窗口高度-元素距离底部的距离(data.bottom)
}).exec()
}
})
},
methods: {
// 减
reduce(item) {
this.cartList.forEach(data => {
if (data.productId == item.productId) {
if (data.count < 1) {
uni.showToast({
title: '数值不能在减了',
icon: 'none'
})
} else {
if (!item.isChecked) {
item.isChecked = !item.isChecked;
}
data.count = data.count - 1;
this.getTotalPrice();
this.getCheckedNum();
}
}
})
this.modifyCart(item);
},
// 加
add(item) {
this.cartList.forEach(data => {
if (data.productId == item.productId) {
if (data.count > 999) {
uni.showToast({
title: '数值不能大于999',
icon: 'none'
})
} else {
if (!item.isChecked) {
item.isChecked = !item.isChecked;
}
data.count = data.count + 1;
this.getTotalPrice();
this.getCheckedNum();
}
}
})
console.log("当前点击的加号的数据是", item);
this.modifyCart(item);
},
// 单选
singleSelect(item) {
console.log("单机情况", item);
item.isChecked = !item.isChecked;
if (!item.isChecked) {
this.allChecked = false;
this.getTotalPrice();
this.getCheckedNum();
} else {
const test = this.cartList.every(item => {
return item.isChecked === true;
});
if (test) {
this.allChecked = true;
this.getTotalPrice();
this.getCheckedNum();
} else {
this.allChecked = false;
this.getTotalPrice();
this.getCheckedNum();
}
}
},
// 全选
selectAll() {
this.allChecked = !this.allChecked
if (this.allChecked) {
this.cartList.map(el => {
el.isChecked = true;
this.getTotalPrice();
this.getCheckedNum();
})
} else {
this.cartList.map(el => {
el.isChecked = false;
this.getTotalPrice();
this.getCheckedNum();
})
}
},
// 计算总价格
getTotalPrice() {
this.totalPrice = 0;
this.cartList.map(item => {
// item.isChecked ? totalPrice += item.count * item.productPrice : totalPrice += 0
if (item.isChecked) {
var sum = item.count * item.productPrice;
this.totalPrice = this.totalPrice + sum;
} else {
this.totalPrice = this.totalPrice + 0
}
})
return this.totalPrice
},
// 获取选中的个数
getCheckedNum() {
this.checkedNum = [];
this.cartList.filter(item => {
if (item.isChecked == true) {
this.checkedNum.push(item)
}
})
},
// 购物车列表滚动条
upper(e) { // 滚动到顶部/左边,会触发 scrolltoupper 事件
// console.log("scrolltoupper 事件", e);
},
// 滚动到底部/右边,会触发 scrolltolower 事件
lower: function(e) {
// console.log(" scrolltolower 事件", e)
},
// 滚动时触发,event.detail = {scrollLeft, scrollTop, scrollHeight, scrollWidth, deltaX, deltaY}
scroll: function(e) {
// console.log("滚动时触发", e)
this.old.scrollTop = e.detail.scrollTop
// this.scrollTop = e.target.offsetTop
},
// 现实弹窗(去结算按钮)
showModal(e) {
if(this.checkedNum.length == 0){
uni.showToast({
title:"请至少选择一个",
icon:'none'
})
}else{
this.modalName = e.currentTarget.dataset.target
}
},
// 确定按钮
confirmModal() {
let that = this;
that.modalName = null
console.log("14455", that.cartList);
console.log("输入的手机号码是", that.iptValue);
uni.setStorageSync("cellPhone", this.iptValue)
let orderProductList = [];
let obj = {};
that.cartList.filter(item => {
if (item.isChecked == true) {
obj = {
"productId": item.productId,
"count": item.count
}
orderProductList.push(obj);
}
})
// 应该先调起支付接口,不管支付成功与否都要订单添加
uni.showLoading({
title:'加载中...',
mask:false
})
let params = {
"orderUserId": that.openid,
"orderUserName": that.userInfo.nickName,
"orderUserPhone": that.iptValue,
"orderProductList": orderProductList
}
orderApi.addOrder(params).then(res => {
console.log("订单添加", res);
if(res.code == 200){
uni.showToast({
icon:'none',
title:res.message
})
uni.navigateTo({
url: '../pendingPayment/pendingPayment',
})
}
uni.hideLoading();
}).catch(err => {
uni.showToast({
icon: 'none',
title: '系统错误请稍后重试'
});
uni.hideLoading();
})
},
// 弹窗
hideModal(e) {
this.modalName = null
},
// 手机号码输入框
iptChange(e) {
this.iptValue = e.detail.value;
},
// 获取购物车列表
getCartList() {
let that = this;
// that.cartList = [];
uni.showLoading({
title:'加载中...',
mask:false
})
let data = {
userId: that.openid,
size: that.size,
current: that.page
}
cartApi.getCart(data).then(res => {
console.log("购物车列表数据是", res);
if (res.code == 200) {
let data = res.data.records;
console.log("所有数据是", data);
if (data.length > 0) {
// that.cartList.push(...data)
that.cartList = data;
// if (that.page == 1) {
// that.cartList = data;
// } else {
// that.cartList = that.cartList.concat(data);
// }
that.cartList.forEach(el => el.isChecked = false);
} else {
that.loadingText = "没有更多了"
// 隐藏刷新按钮
uni.hideNavigationBarLoading();
}
uni.hideLoading();
} else {
uni.showToast({
icon: 'none',
title: '系统错误请稍后重试'
});
uni.hideLoading();
}
}).catch(err => {
uni.showToast({
icon: 'none',
title: '系统错误请稍后重试'
});
uni.hideLoading();
})
},
// ListTouch触摸开始
ListTouchStart(e) {
this.listTouchStart = e.touches[0].pageX
},
// ListTouch计算方向
ListTouchMove(e) {
this.listTouchDirection = e.touches[0].pageX - this.listTouchStart > 0 ? 'right' : 'left'
},
// ListTouch计算滚动
ListTouchEnd(e) {
if (this.listTouchDirection == 'left') {
this.modalName = e.currentTarget.dataset.target
} else {
this.modalName = null
}
this.listTouchDirection = null
},
// 删除购物车
deleteCart(item) {
// console.log("点击的是",item);
let that = this;
cartApi.deleteCart(that.openid, item.productId).then(res => {
console.log("删除购物车数据是", res);
if (res.code == 200) {
that.showCartToast("删除成功", "success")
that.getCartList();
} else {
that.showCartToast("删除失败", "error")
}
}).catch(err => {
that.showCartToast("删除失败", "error")
})
},
// 修改购物车信息
modifyCart(item) {
let that = this;
let params = {
"userId": that.openid,
"productId": item.productId,
"count": item.count
}
cartApi.modifyCart(params).then(res => {
if (res.code == 200) {
console.log("修改成功", res);
}
}).catch(err => {
uni.showToast({
icon: 'none',
title: '系统错误请稍后重试'
});
})
},
showCartToast(title, icon) {
uni.showToast({
title: title,
icon: icon,
duration: 2000
});
},
}
}
</script>
<style lang="scss" scoped>
.choose-state {
position: absolute;
left: 0;
bottom: 35%;
}
.cu-card>.cu-item {
margin: 10rpx 20rpx !important;
padding: 0 20rpx;
}
.cu-list.menu-avatar>.cu-item {
height: 200rpx !important;
}
.image-avatar {
left: 70rpx !important;
}
.image-content {
left: 205rpx !important;
}
.image-price {
display: flex;
align-items: center;
justify-content: center;
}
.scroll-Y {
// height: calc(100% - 42rpx);
margin-bottom: 100rpx;
}
// 加减按钮
.reduce-add {
display: flex;
align-items: center;
justify-content: center;
width: 50%;
}
.image-style {
width: 64rpx;
height: 64rpx;
}
.count-val {
width: 30%;
text-align: center;
color: #000;
}
// 结算按钮
.go-settlement {
position: fixed;
bottom: 0rpx;
width: 100%;
padding-left: 16rpx;
}
.all-choose {
// width: 160px;
flex: 2;
position: relative;
top: 32%;
font-size: 32rpx;
}
.total-price {
flex: 3;
font-size: 40rpx;
}
.total-price .text-price {
color: red;
}
.to-settle {
font-size: 40rpx;
}
.loading {
text-align: center;
line-height: 80rpx;
}
.jie-suan{
text-align: left;
}
</style>
代码你们可以不用管,里面最重要的,也就是要使用的到的是这几句代码:
import cartApi from ‘@/api/shoppingCart/index.js’;
orderApi.addOrder(params).then(res => {
console.log(“订单添加”, res);
if(res.code == 200){
uni.showToast({
icon:‘none’,
title:res.message
})
uni.navigateTo({
url: ‘…/pendingPayment/pendingPayment’,
})
}
uni.hideLoading();
}).catch(err => {
uni.showToast({
icon: ‘none’,
title: ‘系统错误请稍后重试’
});
uni.hideLoading();
})
就是这几句代码。
最后再强调几句:这只是我个人写的简单封装接口,网上肯定有人比我写的更详细,更严谨,仅供参考,望各位大佬见谅,不喜勿喷。感谢!!