Commit 11ecc0b7 authored by 谢卓城's avatar 谢卓城

新增:1.个人中心界面(完成). 2.营销活动界面(完成). 3.确认订单界面(10%).

parent 1aa33f27
No preview for this file type
......@@ -7,11 +7,9 @@ dist
# macOS
.vscode
.DS_Store
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
dist
# Node.js
node_modules/
package/node_modules
dist/miniprogram_npm
/**
* 除继承样式外, app.wxss 中的样式、组件所在页面的的样式对自定义组件无效。
* 参考文档:https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html
* 采用 externalClasses 的方式 在组件.wxml需要的view的class加super-class,可以是多个
* 使用 <Component super-class="<#type#>" />
*/
Component({
properties: {
showDelect: Boolean,
flexList: Array,
title: String // 简化的定义方式
},
externalClasses: ["super-class"],
data: {
content: "content"
},
methods: {
// 这里是一个自定义方法
tagAction(e) {
var eventOption = { content: e.currentTarget.dataset.text }; // 触发事件的选项
this.triggerEvent("tagClick", eventOption);
}
}
});
{
"component": true,
"usingComponents": {}
}
\ No newline at end of file
<!--template/components/index.wxml-->
<view class="container" hover-class="none" hover-stop-propagation="false">
<text class="flex-item super-class" selectable="false" space="false" decode="false" bindtap="tagAction" data-text="{{content}}">{{content}}</text>
</view>
......@@ -13,10 +13,37 @@ Page({
onLoad: function(options) {
console.log("onLoad");
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function() {},
/**
* 生命周期函数--监听页面显示
*/
onShow: function() {},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function() {},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function() {},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function() {
console.log("onShareAppMessage");
}
onShareAppMessage: function() {}
});
.container {
width: 100vw;
.text {
color: red;
}
}
\ No newline at end of file
// pages/index.js
Page({
/**
* 页面的初始数据
*/
data: {
content: "index"
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
console.log("onLoad");
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function() {},
/**
* 生命周期函数--监听页面显示
*/
onShow: function() {},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function() {},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function() {},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function() {}
});
{
"usingComponents": {}
}
\ No newline at end of file
.container {
width: 100vw;
.text {
color: red;
}
}
\ No newline at end of file
<view class='container'>
<text class="text">{{content}}</text>
</view>
\ No newline at end of file
......@@ -38,7 +38,7 @@ const imageFiles = [
/* 清除dist目录 */
gulp.task("clean", done => {
del.sync(["dist/**"]);
del.sync(["dist/**", "!dist/miniprogram_npm"]);
done();
});
......@@ -131,9 +131,10 @@ const newfile = done => {
.example("gulp new -p mypage", "创建mypage的page目录")
.example("gulp new -c mycomponent", "创建mycomponent的component目录")
.example(
"gulp new -s srcfile -p mypage",
"以srcfile为模版创建mypage的page目录"
"gulp new -c mycomponent -t Test",
"以Test为模版创建mypage的component目录"
)
.example("gulp new -p mypage -t Test", "以Test为模版创建mypage的page目录")
.option({
s: {
alias: "src",
......@@ -153,7 +154,12 @@ const newfile = done => {
},
t: {
alias: "template",
describe: "template名称",
describe: "components里的模板",
type: "string"
},
i: {
alias: "index",
describe: "page、components生成的文件与文件夹名称一致",
type: "string"
}
})
......@@ -187,12 +193,25 @@ const newfile = done => {
done();
yargs.parse(["--msg"]);
}
const page = args.t !== undefined ? args.t : "index";
const defaultPath =
source === "template"
? `src/${source}/${type}/*`
: `src/${type}/${source}/*`;
? `./.${source}/${type}/${page}/*`
: `./.${type}/${source}/${page}/*`;
if (args.c !== undefined) {
const component = args.i == "0" ? name.toLowerCase() : "index";
console.log(`"${name}": "../../components/${name}/${component}"`);
}
var stream = gulp.src(defaultPath);
if (args.i == "0") {
stream = stream.pipe(rename({ basename: name.toLowerCase() }));
}
return gulp.src(defaultPath).pipe(gulp.dest(`src/${type}/${name}/`));
return stream.pipe(gulp.dest(`src/${type}/${name}/`));
};
gulp.task("new", newfile);
......@@ -224,7 +243,13 @@ gulp.task(
"watch"
)
);
gulp.task(
"devBuild",
gulp.series(
"clean",
gulp.parallel("wxml", "js", "json", "wxss", "img", "devEnv")
)
);
gulp.task(
"test",
gulp.series(
......
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -4,7 +4,20 @@
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "gulp dev",
"lint": "eslint src --fix",
"devBuild": "gulp devBuild",
"build": "gulp prod",
"build:ci": "sh ./package/miniprogramnpm.sh",
"dev:package": "sh ./package/package.sh -d 1 -u 0 -p",
"package": "sh ./package/package.sh -d 0 -u 0 -p",
"dev:un": "sh ./package/package.sh -d 1 -u 1 -p",
"un": "sh ./package/package.sh -d 0 -u 1 -p",
"page": "gulp new -i 0 -p",
"page:i": "gulp new -p",
"ct": "gulp new -i 0 -c",
"ct:i": "gulp new -c"
},
"repository": {
"type": "git",
......
list=`ls | grep package.sh`
if [ "${#list}" == 0 ];then
echo "########## 进入package文件夹 ##########"
cd package
ls
fi
result=`npm list -g --depth 0 miniprogram-ci | grep @`
if [ "${#result}" == 0 ];then
echo "########## 安装miniprogram-ci ##########"
npm install --save miniprogram-ci -g
else
echo "########## 已经全局安装 miniprogram-ci 直接生成miniprogram_npm ##########"
fi
# 生成miniprogram_npm
miniprogram-ci pack-npm-manually --pack-npm-manually-package-json-path ./package.json --pack-npm-manually-miniprogram-npm-dist-dir ../dist/
\ No newline at end of file
{
"name": "package",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"miniprogram-recycle-view": {
"version": "0.1.5",
"resolved": "https://registry.npmjs.org/miniprogram-recycle-view/-/miniprogram-recycle-view-0.1.5.tgz",
"integrity": "sha512-Pfm/u+jfg+b5zDhjXqm7QbR9IuViqX8JyzcHDgr6Zw9wSK0wmbXNzscA1WoSnGP5Z2nG2TIqtiNXvEbvsyrxXA=="
},
"nmaxios": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/nmaxios/-/nmaxios-1.0.0.tgz",
"integrity": "sha512-RYMOQC02fz0UNu+4ELzmmPXZKfE1Bhi5OORhBXf5TeTratMFLiT5p/o2iSIzRLbTfvQWrnHHqDfUYG5dxF6W9w=="
}
}
}
{
"name": "package",
"version": "1.0.0",
"description": "",
"main": "miniprogramci.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"miniprogram-recycle-view": "^0.1.5",
"nmaxios": "^1.0.0"
},
"devDependencies": {}
}
#!/bin/bash
dev=""
unInstall=""
package=""
cd package
while getopts 'd:u:p:' args;do
case $args in
d)
echo 'use -d :' $OPTARG
dev=$OPTARG
;;
u)
echo 'use -u :' $OPTARG
unInstall=$OPTARG
;;
p)
echo 'use -p :' $OPTARG
package=$OPTARG
;;
esac
done
if [ ! -n "$package" ];then
echo "########## 安装为npm包为不能为空 ##########"
exit 127
fi
echo "########## npm安装包为 $package ##########"
installStr="install"
if [ "$unInstall" == "1" ];then
installStr="uninstall"
fi
echo "########## npm方式: $installStr ##########"
if [ "$dev" == "0" ];then
echo "########## $installStr prod包 ##########"
npm $installStr $package --save
else
echo "########## $installStr dev包 ##########"
npm $installStr $package --save-dev
fi
echo "########## 更新小程序miniprogram_npm包 ##########"
sh ./miniprogramnpm.sh
\ No newline at end of file
/*
* @Author: your name
* @Date: 2020-12-02 09:43:07
* @LastEditTime: 2020-12-31 15:58:07
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: /ChengjingPremiumMember/src/app.js
*/
//app.js
const Request = require("./utils/request.js");
App({
onLaunch: function() {
// 初始化axios
Request.initAxios();
// 展示本地存储能力
var logs = wx.getStorageSync("logs") || [];
logs.unshift(Date.now());
......@@ -33,6 +45,42 @@ App({
}
});
},
_get(url, successCall, failCall) {
wx.showNavigationBarLoading();
Request.axiosGet(
url,
res => {
wx.hideNavigationBarLoading();
successCall && successCall(res);
},
err => {
wx.hideNavigationBarLoading();
failCall && failCall(err);
}
);
},
_post(url, data, successCall, failCall) {
wx.showNavigationBarLoading();
Request.axiosPost(
url,
data,
res => {
wx.hideNavigationBarLoading();
successCall && successCall(res);
},
err => {
wx.hideNavigationBarLoading();
failCall && failCall(err);
}
);
},
toastText: function(text) {
wx.showToast({
title: text,
icon: "success",
duration: 2000
});
},
globalData: {
userInfo: null
}
......
......@@ -3,7 +3,9 @@
"pages/Home/index",
"pages/Cart/index",
"pages/Search/index",
"pages/Order/index"
"pages/Order/index",
"pages/Activity/index",
"pages/UserCenter/usercenter"
],
"entryPagePath": "pages/Home/index",
"tabBar": {
......@@ -17,6 +19,11 @@
"iconPath": "@iconPathAPI",
"selectedIconPath": "@selectedIconPathAPI",
"text": "购物车"
}, {
"pagePath": "pages/UserCenter/usercenter",
"iconPath": "@iconPathAPI",
"selectedIconPath": "@selectedIconPathAPI",
"text": "我的"
}]
},
"networkTimeout": {
......
/**
* 除继承样式外, app.wxss 中的样式、组件所在页面的的样式对自定义组件无效。
* 参考文档:https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html
* 采用 externalClasses 的方式 在组件.wxml需要的view的class加super-class,可以是多个
* 使用 <Component super-class="<#type#>" />
*/
Component({
properties: {
name: String,
phoneNumber: String,
address: String // 简化的定义方式
},
externalClasses: [
"flex",
"flex-c",
"flex-a-c",
"flex-j-b",
"flex-j-a",
"flex-j-a"
],
data: {
content: "content"
},
methods: {
// 这里是一个自定义方法
tagAction(e) {
var eventOption = { content: e.currentTarget.dataset.text }; // 触发事件的选项
this.triggerEvent("tagClick", eventOption);
}
}
});
{
"component": true,
"usingComponents": {}
}
\ No newline at end of file
.container {
width: 100vw;
height: 160rpx;
background-color: rgb(252, 248, 223);
.line {
display: block;
height: 5rpx;
width: 100%;
}
.content-view {
margin: 0 24rpx;
height: 100%;
.name-view {
.name-text {
font-weight:bold;
}
.default-text {
width: 60rpx;
height: 34rpx;
line-height: 34rpx;
font-size: 24rpx;
color: red;
text-align: center;
border: red solid 2rpx;
}
}
.info-view {
.address-text {
font-size: 26rpx;
color: lightgray;
}
}
.arrow {
width: 12rpx;
height: 22rpx;
}
}
}
\ No newline at end of file
<!--template/components/index.wxml-->
<view class="container" hover-class="none" hover-stop-propagation="false">
<image class="line" src="../../images/address.png"/>
<view class="content-view flex flex-a-c flex-j-a" hover-class="none" hover-stop-propagation="false">
<view class="name-view flex flex-c flex-a-c" hover-class="none" hover-stop-propagation="false">
<text class="name-text" selectable="false" space="false" decode="false">{{name}}</text>
<text class="default-text" selectable="false" space="false" decode="false">默认</text>
</view>
<view class="info-view flex flex-c" hover-class="none" hover-stop-propagation="false">
<text class="iphone-text" selectable="false" space="false" decode="false">{{phoneNumber}}</text> <text class="address-text" selectable="false" space="false" decode="false">{{address}}</text>
</view>
<image class="arrow" src="../../images/blackback.png" />
</view>
</view>
/**
* 除继承样式外, app.wxss 中的样式、组件所在页面的的样式对自定义组件无效。
* 参考文档:https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html
* 采用 externalClasses 的方式 在组件.wxml需要的view的class加super-class,可以是多个
* 使用 <Component super-class="<#type#>" />
*/
Component({
properties: {
idx: Number,
count: Number,
icon: String,
title: String // 简化的定义方式
},
externalClasses: [
"flex",
"flex-j-b",
"flex-c",
"text-c",
"flex-a-c",
"flex-j-a",
"flex-j-c",
"tag-width"
],
data: {},
methods: {
// 这里是一个自定义方法
tagAction(e) {
var eventOption = { idx: e.currentTarget.dataset.index }; // 触发事件的选项
this.triggerEvent("tagClick", eventOption);
}
}
});
{
"component": true,
"usingComponents": {}
}
\ No newline at end of file
.container {
.count-view {
display: inline-block;
position: absolute;
.count-text {
display: inline-block;
position: relative;
color: white;
background-color: red;
width: 40rpx;
height: 40rpx;
border-radius: 20rpx;
line-height: 40rpx;
text-align: center;
top: -50rpx;
left: 30rpx;
font-size: 26rpx;
}
}
image {
width: 46rpx;
height: 46rpx;
}
.icon-text {
margin-top: 10rpx;
}
}
\ No newline at end of file
<!--template/components/index.wxml-->
<view class="container flex flex-c flex-a-c flex-j-c tag-width" hover-class="none" hover-stop-propagation="false" bind:tap="tagAction" data-index="{{idx}}">
<view class="count-view" hover-class="none" hover-stop-propagation="false" wx:if="{{count > 0}}">
<text class="count-text">{{count}}</text>
</view>
<image src="{{icon}}" />
<text class="icon-text" selectable="false" space="false" decode="false">{{title}}</text>
</view>
/**
* 除继承样式外, app.wxss 中的样式、组件所在页面的的样式对自定义组件无效。
* 参考文档:https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html
* 采用 externalClasses 的方式 在组件.wxml需要的view的class加super-class,可以是多个
* 使用 <Component super-class="<#type#>" />
*/
let App = getApp();
Component({
properties: {
showDelect: Boolean,
flexList: Array,
title: String // 简化的定义方式
},
externalClasses: ["flex", "flex-j-b", "flex-c", "text-c"],
data: {
content: "content"
},
methods: {
// 这里是一个自定义方法
tagAction(e) {
var eventOption = { content: e.currentTarget.dataset.text }; // 触发事件的选项
this.triggerEvent("tagClick", eventOption);
},
iconClick() {
App.toastText("头像点击!");
},
punchInAction() {
App.toastText("签到成功!");
}
}
});
{
"component": true,
"usingComponents": {}
}
\ No newline at end of file
.container {
width: 100vw;
height: 310rpx;
.header {
width: 100vw;
.user-view {
display: flex;
margin-top: 80rpx;
margin-left: 30rpx;
.user-info {
margin-left: 10rpx;
.members-text {
display: inline-block;
width: 150rpx;
border-radius: 19rpx;
border: royalblue solid 1rpx;
}
text {
font-size: 26rpx;
color: royalblue;
}
}
}
.header-icon {
border-radius: 64rpx;
width: 137rpx;
height: 137rpx;
}
.qr-code {
width: 60rpx !important;
height: 60rpx !important;
margin-top: 20rpx;
margin-right: 20rpx;
border: rgba($color: #ffffff, $alpha: 0.8) solid 10rpx;
border-radius: 8rpx;
}
}
.bottom {
display: flex;
width: 100vw;
height: 50rpx;
background-color: rgba($color: #000000, $alpha: 0.5);
justify-content: space-around;
text {
font: 26rpx;
color: white;
}
}
.bg-icon {
width: 100%;
height: 100%;
}
}
\ No newline at end of file
<!--template/components/index.wxml-->
<view class="container flex-c flex flex-j-b" style="background: url('../../images/bg.png')">
<!-- <image class="bg-icon" src="../../images/bg.png" lazy-load="false" > -->
<view class="header flex flex-j-b" hover-class="none" hover-stop-propagation="false">
<view class="user-view" hover-class="none" hover-stop-propagation="false">
<image class="header-icon" src="../../images/group_portrait.png" bind:tap="iconClick"/>
<view class="user-info flex flex-c flex-j-b" hover-class="none" hover-stop-propagation="false">
<text >清风</text>
<text >会员id:{{1333343296}}</text>
<text class="members-text text-c">青铜会员</text>
</view>
</view>
<image class="qr-code" src="../../images/shop_code.png" lazy-load="false" binderror="" bindload=""></image>
</view>
<view class="bottom" hover-class="none" hover-stop-propagation="false">
<text >余额:{{296}}</text>
<text >积分:{{296}}</text>
<text bind:tap="punchInAction">点击签到</text>
</view>
</view>
/**
* 除继承样式外, app.wxss 中的样式、组件所在页面的的样式对自定义组件无效。
* 参考文档:https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html
* 采用 externalClasses 的方式 在组件.wxml需要的view的class加super-class,可以是多个
* 使用 <Component super-class="<#type#>" />
*/
let App = getApp();
Component({
properties: {
showDelect: Boolean,
flexList: Array,
title: String // 简化的定义方式
},
externalClasses: [
"flex",
"flex-j-b",
"flex-c",
"text-c",
"flex-a-c",
"flex-j-a",
"flex-j-c"
],
data: {
content: "content",
list: [
{ title: "待付款", icon: "../../images/waitpay.png", count: 0 },
{ title: "待发货", icon: "../../images/waitsent.png", count: 1 },
{ title: "待收货", icon: "../../images/waitpick.png", count: 2 },
{ title: "待评价", icon: "../../images/unReview.png", count: 0 },
{ title: "退换货", icon: "../../images/waitsent.png", count: 1 }
]
},
methods: {
// 这里是一个自定义方法
tagAction(e) {
let item = this.data.list[e.detail.idx];
if (item.count > 0) {
item.count = 0;
} else {
item.count = Math.ceil(Math.random() * 15);
}
console.log(item);
App.toastText(item.title);
this.setData({
list: this.data.list
});
// var eventOption = { content: e.currentTarget.dataset.text }; // 触发事件的选项
// this.triggerEvent("tagClick", eventOption);
}
}
});
{
"component": true,
"usingComponents": {
"TagButton": "../../components/TagButton/index"
}
}
\ No newline at end of file
.container {
width: 100vw;
.title-view {
margin: 0 20rpx;
height: 100rpx;
border-bottom: rgb(235, 237, 236) solid 2rpx;
image {
width: 12rpx;
height: 22rpx;
}
}
.tag-container {
height: 170rpx;
align-items: center;
border-bottom: rgb(235, 237, 236) solid 20rpx;
}
}
\ No newline at end of file
<!--template/components/index.wxml-->
<view class="container" hover-class="none" hover-stop-propagation="false">
<view class="title-view flex flex-j-b flex-a-c" hover-class="none" hover-stop-propagation="false">
<text selectable="false" space="false" decode="false">我的订单</text>
<image src="../../images/grayback.png" />
</view>
<view class="tag-container flex flex-j-a" hover-class="none" hover-stop-propagation="false">
<block wx:for="{{list}}" wx:key="index" wx:for-item="item">
<TagButton title="{{item.title}}" icon="{{item.icon}}" count="{{item.count}}" flex="flex" flex-j-b="flex-j-b" flex-c="flex-c" flex-a-c="flex-a-c" flex-j-a="flex-j-a" flex-j-c="flex-j-c" bind:tagClick="tagAction" idx="{{index}}"/>
</block>
</view>
</view>
/**
* 除继承样式外, app.wxss 中的样式、组件所在页面的的样式对自定义组件无效。
* 参考文档:https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html
* 采用 externalClasses 的方式 在组件.wxml需要的view的class加super-class,可以是多个
* 使用 <Component super-class="<#type#>" />
*/
Component({
properties: {
showDelect: Boolean,
flexList: Array,
title: String // 简化的定义方式
},
externalClasses: ["flex", "flex-c", "flex-j-c", "flex-w", "flex-a-c"],
data: {
list: [
{
title: "优惠卷",
icon: "../../images/waitpay.png",
subTitle: "活动优惠卷"
},
{
title: "奖品",
icon: "../../images/waitsent.png",
subTitle: "丰富奖品"
},
{
title: "生日礼品",
icon: "../../images/waitpick.png",
subTitle: "会员生日惊喜"
},
{
title: "营销活动",
icon: "../../images/unReview.png",
subTitle: "营销活动"
}
]
},
methods: {
// 这里是一个自定义方法
tagAction(e) {
var eventOption = { content: e.currentTarget.dataset.text }; // 触发事件的选项
this.triggerEvent("tagClick", eventOption);
}
}
});
{
"component": true,
"usingComponents": {}
}
\ No newline at end of file
.container {
width: 100vw;
margin-bottom: 75rpx;
.title-view {
height: 90rpx;
margin: 0 20rpx;
border-bottom: rgb(235, 237, 236) solid 2rpx;
}
.icon-container {
margin: 0 20rpx;
.icon-view {
width: calc( (100vw - 40rpx) / 2.0);
height: 140rpx;
border-bottom: rgb(235, 237, 236) solid 2rpx;
image {
width: 66rpx;
height: 66rpx;
}
.text-container {
margin-left: 30rpx;
.title {
font-size: 35rpx;
}
.subTitle {
color: lightgray;
font-size: 30rpx;
}
}
}
}
}
\ No newline at end of file
<!--template/components/index.wxml-->
<view class="container" hover-class="none" hover-stop-propagation="false">
<view class="title-view flex flex-c flex-j-c" hover-class="none" hover-stop-propagation="false">
<text>我的优惠</text>
</view>
<view class="icon-container flex flex-w" >
<block wx:for="{{list}}" wx:for-item="item" wx:key="index">
<view class="icon-view flex flex-j-c flex-a-c" hover-class="none" hover-stop-propagation="false">
<image src="{{item.icon}}" />
<view class="text-container flex flex-c" hover-class="none" hover-stop-propagation="false">
<text class="title">{{item.title}}</text>
<text class="subTitle">{{item.subTitle}}</text>
</view>
</view>
</block>
</view>
</view>
/*
* @Author: your name
* @Date: 2020-12-25 11:16:04
* @LastEditTime: 2020-12-31 16:01:22
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: /ChengjingPremiumMember/src/components/UserService/index.js
*/
/**
* 除继承样式外, app.wxss 中的样式、组件所在页面的的样式对自定义组件无效。
* 参考文档:https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html
* 采用 externalClasses 的方式 在组件.wxml需要的view的class加super-class,可以是多个
* 使用 <Component super-class="<#type#>" />
*/
let App = getApp();
Component({
properties: {
showDelect: Boolean,
flexList: Array,
title: String // 简化的定义方式
},
externalClasses: ["flex", "flex-c", "flex-j-c", "flex-w", "flex-a-c"],
data: {
list: [
{ title: "积分商城", icon: "../../images/integral.png" },
{ title: "余额", icon: "../../images/balance.png" },
{ title: "充值", icon: "../../images/recharge.png" },
{ title: "绑定老卡", icon: "../../images/value_card.png" },
{ title: "会员信息", icon: "../../images/memInfo.png" },
{ title: "附近门店", icon: "../../images/stores.png" },
{ title: "预约", icon: "../../images/reservation.png" },
{ title: "客服中心", icon: "../../images/service.png" },
{ title: "收藏", icon: "../../images/favorite.png" },
{ title: "账户安全", icon: "../../images/waitsent.png" },
{ title: "系统消息", icon: "../../images/sys_news.png" },
{ title: "消费查询", icon: "../../images/waitsent.png" }
]
},
methods: {
// 这里是一个自定义方法
tagAction(e) {
let item = this.data.list[e.detail.idx];
console.log(item);
App.toastText(item.title);
// var eventOption = { content: e.currentTarget.dataset.text }; // 触发事件的选项
// this.triggerEvent("tagClick", eventOption);
}
}
});
{
"component": true,
"usingComponents": {
"TagButton": "../../components/TagButton/index"
}
}
\ No newline at end of file
.container {
width: 100vw;
border-bottom: rgb(235, 237, 236) solid 20rpx;
.title-view {
height: 90rpx;
margin: 0 20rpx;
}
.tag-container {
margin: 0 20rpx;
.tag-width {
border-top: rgb(235, 237, 236) solid 2rpx;
width: calc( (100vw - 40rpx) / 4.0 );
height: 180rpx;
}
}
}
\ No newline at end of file
<!--template/components/index.wxml-->
<view class="container" hover-class="none" hover-stop-propagation="false">
<view class="title-view flex flex-c flex-j-c" hover-class="none" hover-stop-propagation="false">
<text>我的服务</text>
</view>
<view class="tag-container flex flex-w" hover-class="none" hover-stop-propagation="false">
<block wx:for="{{list}}" wx:key="index" wx:for-item="item">
<TagButton title="{{item.title}}" icon="{{item.icon}}" count="{{item.count}}" flex="flex" flex-j-b="flex-j-b" flex-c="flex-c" flex-a-c="flex-a-c" flex-j-a="flex-j-a" flex-j-c="flex-j-c" tag-width="tag-width" bind:tagClick="tagAction" idx="{{index}}"/>
</block>
</view>
</view>
......@@ -2,8 +2,8 @@
* @Descripttion: 开发环境
*/
const API_URL = {
host: "http://xxdev.xxx.com",
r: "https://xxr.xxx.com"
host: "https://weapp.changein.cn",
uniacid: "10001" // 默认即可,勿填
};
module.exports = API_URL;
......@@ -2,7 +2,7 @@
* @Descripttion: 生产环境
*/
const API_URL = {
host: "http://xxprod.xxx.com",
r: "https://xxr.xxx.com"
host: "https://weapp.changein.cn",
uniacid: "10001" // 默认即可,勿填
};
module.exports = API_URL;
......@@ -2,7 +2,7 @@
* @Descripttion: 测试环境
*/
const API_URL = {
host: "http://xxtest.xxx.com",
r: "https://xxr.xxx.com"
host: "https://weapp.changein.cn",
uniacid: "10001" // 默认即可,勿填
};
module.exports = API_URL;
// pages/index.js
Page({
/**
* 页面的初始数据
*/
data: {
content: "index",
list: [
{ title: "明心活动", time: "2019-1-2" },
{ title: "明心活动", time: "2019-1-2" }
]
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
console.log("onLoad");
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function() {},
/**
* 生命周期函数--监听页面显示
*/
onShow: function() {},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function() {},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function() {},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function() {}
});
{
"usingComponents": {},
"navigationBarTitleText": "营销活动"
}
\ No newline at end of file
.container {
width: 100vw;
.cell {
.title-view {
margin: 60rpx 20rpx 0 20rpx;
text {
color: black;
}
}
image {
display: inline-block;
width: calc( 100vw - 40rpx );
margin: 20rpx 20rpx 40rpx 20rpx;
border-radius: 10rpx;
}
}
.line {
background-color: lightcyan;
height: 20rpx;
width: 100%;
}
}
\ No newline at end of file
<view class='container'>
<block wx:for="{{list}}" wx:key="index" wx:for-item="item">
<view class="cell" hover-class="none" hover-stop-propagation="false" ::key="key">
<view class="title-view display-flex flex-j-between" hover-class="none" hover-stop-propagation="false">
<text>{{item.title}}</text>
<text>{{item.time}}</text>
</view>
<image src="../../images/640.jpeg" />
</view>
<view class="line" hover-class="none" hover-stop-propagation="false" wx:if="{{list.length-1 != index}}" />
</block>
</view>
\ No newline at end of file
......@@ -25,12 +25,7 @@ Page({
* 生命周期函数--监听页面加载
*/
onLoad: function() {
setTimeout(() => {
this.setData({
loading: false
});
this.loadNewData();
}, 2000);
},
loadMoreData() {
let goods = this.data.goodsList;
......
let App = getApp();
Page({
/**
* 页面的初始数据
......@@ -53,15 +55,21 @@ Page({
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
// this.setData({
// search: this.search.bind(this)
// })
setTimeout(() => {
this.setData({
loading: false
});
this.loadNewData();
}, 2000);
App._get(
"page/home",
res => {
console.log("发起get请求-res", res);
},
err => {
console.log("发起get请求-err", err);
}
);
},
/**
* 页面相关事件处理函数--监听用户下拉动作
......@@ -104,11 +112,11 @@ Page({
});
},
cellAction: function(e) {
this.showToastText("点击了" + e.currentTarget.dataset["index"]);
App.toastText("点击了" + e.currentTarget.dataset["index"]);
console.log("cellAction result", e.currentTarget.dataset["index"]);
},
classificationAction: function(e) {
this.showToastText("点击了" + e.currentTarget.dataset["index"]);
App.toastText("点击了" + e.currentTarget.dataset["index"]);
console.log(
"classificationAction result",
e.currentTarget.dataset["index"]
......@@ -121,12 +129,5 @@ Page({
onReachBottom: function(e) {
this.loadMoreData();
console.log("onReachBottom result", this.data.iconList);
},
showToastText: function(text) {
wx.showToast({
title: text,
icon: "success",
duration: 2000
});
}
});
{
"usingComponents": {},
"usingComponents": {
"AddressView": "../../components/AddressView/index"
},
"navigationBarTitleText": "确认订单"
}
\ No newline at end of file
<!--pages/Order/index.wxml-->
<view class="container" hover-class="none" hover-stop-propagation="false">
<view class="search-container" hover-class="none" hover-stop-propagation="false">
<text class="search-text" user-select="false" space="false" decode="false">
待开发...
</text>
</view>
<!--/components/UserService-->
<AddressView flex="display-flex" flex-c="flex-column" flex-a-c="flex-a-center" flex-j-b="flex-j-between" flex-j-a="flex-j-around" flex-j-c="flex-j-center" name="张先生" address="天津市海滨新区中新天津生态城满天大道11号" phoneNumber="133****9965"/>
</view>
// pages/index.js
Page({
/**
* 页面的初始数据
*/
data: {
content: "index"
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
console.log("onLoad");
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function() {},
/**
* 生命周期函数--监听页面显示
*/
onShow: function() {},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function() {},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function() {},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function() {},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function() {}
});
{
"usingComponents": {
"UserHeaderView": "../../components/UserHeaderView/index",
"UserOrder": "../../components/UserOrder/index",
"UserPreferential": "../../components/UserPreferential/index",
"UserService": "../../components/UserService/index"
},
"navigationBarTitleText": "个人中心"
}
\ No newline at end of file
.container {
width: 100vw;
}
\ No newline at end of file
<view class='container'>
<!--/components/UserHeaderView-->
<UserHeaderView flex="display-flex" flex-j-b="flex-j-between" flex-c="flex-column" text-c="text-center"/>
<!--template/components/UserOrder-->
<UserOrder flex="display-flex" flex-j-b="flex-j-between" flex-c="flex-column" text-c="text-center" flex-a-c="flex-a-center" flex-j-a="flex-j-around" flex-j-c="flex-j-center"/>
<!--/components/UserService-->
<UserService flex="display-flex" flex-c="flex-column" flex-j-c="flex-j-center" flex-w="flex-wrap" flex-a-c="flex-a-center"/>
<!--/components/UserPreferential-->
<UserPreferential flex="display-flex" flex-c="flex-column" flex-j-c="flex-j-center" flex-w="flex-wrap" flex-a-c="flex-a-center"/>
</view>
\ No newline at end of file
......@@ -17,8 +17,8 @@
"uglifyFileName": false,
"uploadWithSourceMap": true,
"useIsolateContext": true,
"nodeModules": false,
"enhance": false,
"nodeModules": true,
"enhance": true,
"useCompilerModule": true,
"userConfirmedUseCompilerModuleSwitch": false,
"useMultiFrameRuntime": false,
......
export function beforeFn(fn, inject) {
return (...args) => {
try {
inject(...args);
fn.call(this, ...args);
} catch (error) {
console.warn(error);
fn.call(this, ...args);
}
};
}
export function afterFn(fn, inject) {
return (...args) => {
try {
fn.call(this, ...args);
inject(...args);
} catch (error) {
console.warn(error);
fn.call(this, ...args);
}
};
}
import ExpireCache from './ExpireCache';
export default class Buffer extends ExpireCache {
static cacheMap = new Map();
}
export default class CacheItem {
/**
* 缓存item
* @param {Any} data 缓存数据
* @param {Number} timeout 缓存时长,计算缓存过期时间,单位-秒
* @param {Any} cacheLabel 缓存标记,对比标记极端缓存是否过期
*/
constructor(data, timeout, cacheLabel = null) {
this.data = data;
this.cacheLabel = cacheLabel;
this.expireTime = timeout ? new Date().getTime() + timeout * 1000 : null;
}
}
import CacheItem from './CacheItem';
export default class ExpireCache extends CacheItem {
constructor(data, timeout, cacheLabel) {
super(data, timeout, cacheLabel);
}
// 定义静态数据map来作为缓存池
static cacheMap = new Map();
// 数据是否过期
static isExpire(name, curCacheLabel) {
const data = this.cacheMap.get(name);
// 没有数据 一定过期
if (!data) return true;
// 获取系统当前时间戳
const { expireTime, cacheLabel } = data;
const currentTime = new Date().getTime();
// 缓存含过期时间&&已过期
const timeExpire = expireTime && currentTime > expireTime;
// 缓存含过期标记&&标记已变化
const labelExpire = curCacheLabel && cacheLabel && curCacheLabel !== cacheLabel;
if (timeExpire || labelExpire) {
this.cacheMap.delete(name);
return true;
}
// 不过期
return false;
}
// 当前data在 cache 中是否过期 - 判断时间&标记
static has(name, cacheLabel) {
return !this.isExpire(name, cacheLabel);
}
// 删除
static delete(name) {
return this.cacheMap.delete(name);
}
/**
* 获取,如有过期标记需要传入过期标记或者先用has判断
* @param {Any} name 缓存名称
* @param {Any} cacheLabel 缓存标记
*/
static get(name, cacheLabel) {
return this.has(name, cacheLabel) ? this.cacheMap.get(name).data : null;
}
// 存储
static set(name, data, timeout, cacheLabel) {
const itemCache = new ExpireCache(data, timeout, cacheLabel);
// 缓存
this.cacheMap.set(name, itemCache);
}
}
import ExpireCache from './ExpireCache';
import StorageMap from './StorageMap';
export default class Storage extends ExpireCache {
static cacheMap = new StorageMap();
static getCacheName(name) {
return `${INJECTION_FROM_WEBPACK.serverType}iyourcar_cache_${name}`;
}
}
export default class StorageMap {
static getCacheName(name) {
// INJECTION_FROM_WEBPACK.serverType用户区分当前环境
return `${"INJECTION_FROM_WEBPACK.serverType"}iyourcar_cache_${name}`;
}
get(name) {
let storageData = null;
try {
storageData = wx.getStorageSync(name);
} catch (e) {}
return storageData;
}
set(name, data) {
wx.setStorage({
key: name,
data,
});
}
delete(name) {
wx.removeStorageSync(name);
}
}
export const storageMap = new StorageMap();
const API_URL = require("../env.js");
import axios from "nmaxios";
/**
* 初始化网络配置,会覆盖默认配置
*/
function initAxios() {
const baseUrl = API_URL.host + "/index.php?s=/api/";
const header = {
"content-type": "application/x-www-form-urlencoded; charset=UTF-8"
};
const transformRequest = data => {
return {
/// 这是使用transformRequest给请求参数加上的字段
wxapp_id: API_URL.uniacid,
...data
};
};
const transformResponse = res => ({
...res
// transformResponse: "这是使用transformResponse给response加上的字段"
});
const resolveWrap = res => {
// console.log("resolveWrap:", "这里可以统一处理resolve状态");
return res.data;
};
const rejectWrap = res => {
// console.log("rejectWrap:", "这里可以统一处理reject状态");
return res;
};
const validateStatus = res => {
console.log(
"validateStatus:",
"使用validateStatus验证请求状态为2xx时才resolve"
);
return /^2/.test(res.statusCode.toString());
};
axios.creat({
baseUrl,
header,
validateStatus,
transformRequest,
transformResponse,
resolveWrap,
rejectWrap
});
}
/**
* axios的Get请求
* @param {url} url
* @param {successCall} 成功回调
* @param {failCall} 失败回调
*/
function axiosGet(url, successCall, failCall) {
axios
.get(url)
.then(res => {
// console.log("发起get请求-res", res);
successCall && successCall(res);
})
.catch(err => {
// console.log("发起get请求-err", err);
failCall && failCall(err);
});
}
/**
* axios的Post请求
* @param {url} url
* @param {data} 参数
* @param {successCall} 成功回调
* @param {failCall} 失败回调
*/
function axiosPost(url, data, successCall, failCall) {
axios
.post(url, data)
.then(res => {
// console.log("发起post请求-res", res);
successCall && successCall(res);
})
.catch(err => {
// console.log("发起post请求-err", err);
failCall && failCall(err);
});
}
module.exports = {
initAxios,
axiosGet,
axiosPost
};
# 基于 wx.request 封装的类 axios 请求
## Introduction
- wx.request 的配置、axios 的调用方式
## feature
- 支持 wx.request 所有配置项
- 支持 axios 调用方式
- 支持 自定义 baseUrl
- 支持 自定义响应状态码对应 resolve 或 reject 状态
- 支持 对响应(resolve/reject)分别做统一的额外处理
- 支持 转换请求数据和响应数据
- 支持 请求缓存(内存或本地缓存),可设置缓存标记、过期时间
## use
### app.js @onLaunch
```javascript
axios.creat({
header: {
content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
baseUrl: 'https://api.baseurl.com',
...
});
```
### page.js
```javascript
axios
.post("/url", { id: 123 })
.then((res) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
```
## API
```javascript
axios(config) - 默认get
axios(url[, config]) - 默认get
axios.get(url[, config])
axios.post(url[, data[, config]])
axios.cache(url[, data[, config]]) - 缓存请求(内存)
axios.cache.storage(url[, data[, config]]) - 缓存请求(内存 & local storage
axios.creat(config) - 初始化定制配置,覆盖默认配置
```
## config
默认配置项说明
```javascript
export default {
// 请求接口地址
url: undefined,
// 请求的参数
data: {},
// 请求的 header
header: "application/json",
// 超时时间,单位为毫秒
timeout: undefined,
// HTTP 请求方法
method: "GET",
// 返回的数据格式
dataType: "json",
// 响应的数据类型
responseType: "text",
// 开启 http2
enableHttp2: false,
// 开启 quic
enableQuic: false,
// 开启 cache
enableCache: false,
/** 以上为wx.request的可配置项,参考 https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html */
/** 以下为wx.request没有的新增配置项 */
// {String} baseURL` 将自动加在 `url` 前面,可以通过设置一个 `baseURL` 便于传递相对 URL
baseUrl: "",
// {Function} (同axios的validateStatus)定义对于给定的HTTP 响应状态码是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 reject
validateStatus: undefined,
// {Function} 请求参数包裹(类似axios的transformRequest),通过它可统一补充请求参数需要的额外信息(appInfo/pageInfo/场景值...),需return data
transformRequest: undefined,
// {Function} resolve状态下响应数据包裹(类似axios的transformResponse),通过它可统一处理响应数据,需return res
transformResponse: undefined,
// {Function} resolve状态包裹,通过它可做接口resolve状态的统一处理
resolveWrap: undefined,
// {Function} reject状态包裹,通过它可做接口reject状态的统一处理
rejectWrap: undefined,
// {Boolean} _config.useCache 是否开启缓存
useCache: false,
// {String} _config.cacheName 缓存唯一key值,默认使用url&data生成
cacheName: undefined,
// {Boolean} _config.cacheStorage 是否开启本地缓存
cacheStorage: false,
// {Any} _config.cacheLabel 缓存标志,请求前会对比该标志是否变化来决定是否使用缓存,可用useCache替代
cacheLabel: undefined,
// {Number} _config.cacheExpireTime 缓存时长,计算缓存过期时间,单位-秒
cacheExpireTime: undefined,
};
```
/**
* Axios.js
*/
/* eslint-disable no-underscore-dangle */
import wxRequest from './wxRequest';
import defaults from './defaults';
import { combineUrl, mergeConfig } from './util';
import Buffer from '../utils/cache/Buffer';
import Storage from '../utils/cache/Storage';
import StorageMap from '../utils/cache/StorageMap';
class Axios {
constructor(config = defaults) {
this.defaultConfig = config;
}
/**
* 初始化用户配置,会覆盖默认配置
* @param {Object} _config 配置
*/
creat(_config = {}) {
this.defaultConfig = mergeConfig(this.defaultConfig, _config);
}
axios($1 = {}, $2 = {}) {
let config = $1;
// 兼容axios(url[, config])方式
if (typeof $1 === 'string') {
config = $2;
config.url = $1;
}
return this.request(config);
}
get(url, _config = {}) {
const config = {
..._config,
url,
method: 'GET',
};
return this.request(config);
}
post(url, data = {}, _config = {}) {
const config = {
..._config,
url,
data,
method: 'POST',
};
return this.request(config);
}
/**
* 请求缓存api,缓存于内存中
*/
cache(url, data = {}, _config = {}) {
const config = {
..._config,
url,
data,
method: 'POST',
};
return this._cache(config);
}
/**
* 请求缓存api,缓存于本地缓存中
*/
storage(url, data = {}, _config = {}) {
const config = {
..._config,
url,
data,
method: 'POST',
cacheStorage: true,
};
return this._cache(config);
}
/**
* 请求缓存
* @param {Object} _config 配置
* @param {Boolean} _config.useCache 是否开启缓存
* @param {String} _config.cacheName 缓存唯一key值,默认使用url&data生成
* @param {Boolean} _config.cacheStorage 是否开启本地缓存
* @param {Any} _config.cacheLabel 缓存标志,请求前会对比该标志是否变化来决定是否使用缓存,可用useCache替代
* @param {Number} _config.cacheExpireTime 缓存时长,计算缓存过期时间,单位-秒
*/
_cache(_config) {
const {
url = '',
data = {},
useCache = true,
cacheName: _cacheName,
cacheStorage,
cacheLabel,
cacheExpireTime,
} = _config;
const computedCacheName = _cacheName || `${url}#${JSON.stringify(data)}`;
const cacheName = StorageMap.getCacheName(computedCacheName);
// return buffer
if (useCache && Buffer.has(cacheName, cacheLabel)) {
return Buffer.get(cacheName);
}
// return storage
if (useCache && cacheStorage) {
if (Storage.has(cacheName, cacheLabel)) {
const data = Storage.get(cacheName);
// storage => buffer
Buffer.set(
cacheName,
Promise.resolve(data),
cacheExpireTime,
cacheLabel
);
return Promise.resolve(data);
}
}
const curPromise = new Promise((resolve, reject) => {
const handleFunc = (res) => {
// do storage
if (useCache && cacheStorage) {
Storage.set(cacheName, res, cacheExpireTime, cacheLabel);
}
return res;
};
this._request(_config)
.then((res) => {
resolve(handleFunc(res));
})
.catch(reject);
});
// do buffer
Buffer.set(cacheName, curPromise, cacheExpireTime, cacheLabel);
return curPromise;
}
request(_config) {
// config支持缓存
if (_config.useCache) return this._cache(_config);
return this._request(_config);
}
_request(_config = {}) {
let config = mergeConfig(this.defaultConfig, _config);
const { baseUrl, url, header, data = {}, transformRequest } = config;
const computedConfig = {
header: {
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
ycFrom: 'yc-component',
...header,
},
...(baseUrl && {
url: combineUrl(url, baseUrl),
}),
...(transformRequest &&
typeof transformRequest === 'function' && {
data: transformRequest(data),
}),
};
config = mergeConfig(config, computedConfig);
// console.log('iyourcar-component-axios__request-config :', config);
return wxRequest(config);
}
}
export default Axios;
/**
* 基于wx.request封装的类axios请求
* wx.request 的配置、axios的调用方式
* @config 配置参数说明 --> ./defaults.js
* @api axios(config) - 默认get
* @api axios(url[, config]) - 默认get
* @api axios.get(url[, config])
* @api axios.post(url[, data[, config]])
* @api axios.cache(url[, data[, config]]) - 缓存请求(内存)
* @api axios.cache.storage(url[, data[, config]]) - 缓存请求(内存 & local storage)
* @api axios.creat(config) - 初始化定制配置,覆盖默认配置
* @use @app.js-onLaunch:axios.creat(config); @page.js: axios.post(url[, data[, config]]);
* @reference http://www.axios-js.com/zh-cn/docs/
*/
import Axios from './axios.class.js';
const axiosInstance = new Axios();
const { axios } = axiosInstance;
axios.creat = axiosInstance.creat.bind(axiosInstance);
axios.get = axiosInstance.get.bind(axiosInstance);
axios.post = axiosInstance.post.bind(axiosInstance);
axios.cache = axiosInstance.cache.bind(axiosInstance);
axios.cache.storage = axiosInstance.storage.bind(axiosInstance);
export default axios;
/** config - axios默认配置项 */
const API_URL = require("../../env.js");
export default {
// 请求接口地址
url: undefined,
// 请求的参数
data: {},
// 请求的 header
header: "application/json",
// 超时时间,单位为毫秒
timeout: undefined,
// HTTP 请求方法
method: "GET",
// 返回的数据格式
dataType: "json",
// 响应的数据类型
responseType: "text",
// 开启 http2
enableHttp2: false,
// 开启 quic
enableQuic: false,
// 开启 cache
enableCache: false,
/** 以上为wx.request的可配置项,参考 https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html */
/** 以下为wx.request没有的新增配置项 */
// {String} baseURL` 将自动加在 `url` 前面,可以通过设置一个 `baseURL` 便于传递相对 URL
baseUrl: API_URL,
// {Function} (同axios的validateStatus)定义对于给定的HTTP 响应状态码是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 reject
validateStatus: undefined,
// {Function} 请求参数包裹(类似axios的transformRequest),通过它可统一补充请求参数需要的额外信息(appInfo/pageInfo/场景值...),需return data
transformRequest: undefined,
// {Function} resolve状态下响应数据包裹(类似axios的transformResponse),通过它可统一处理响应数据,需return res
transformResponse: undefined,
// {Function} resolve状态包裹,通过它可做接口resolve状态的统一处理
resolveWrap: undefined,
// {Function} reject状态包裹,通过它可做接口reject状态的统一处理
rejectWrap: undefined,
// {Boolean} _config.useCache 是否开启缓存
useCache: false,
// {String} _config.cacheName 缓存唯一key值,默认使用url&data生成
cacheName: undefined,
// {Boolean} _config.cacheStorage 是否开启本地缓存
cacheStorage: false,
// {Any} _config.cacheLabel 缓存标志,请求前会对比该标志是否变化来决定是否使用缓存,可用useCache替代
cacheLabel: undefined,
// {Number} _config.cacheExpireTime 缓存时长,计算缓存过期时间,单位-秒
cacheExpireTime: undefined
};
let scene = '';
export function getPageInfo() {
const postData = {};
try {
if (!scene) {
scene = wx.getLaunchOptionsSync().scene || '';
}
postData.scene = scene;
} catch (error) {
//
}
const pageList = getCurrentPages();
if (pageList.length) {
const currentPage = pageList[pageList.length - 1];
const defaultOptions = JSON.stringify({ default: true });
postData.currentPage = currentPage.__route__;
const optionNameList = ['op', 'options', 'option'];
postData.currentOptions = defaultOptions;
optionNameList.forEach((i) => {
const option = currentPage.data[i] || currentPage[i];
if (option) {
postData.currentOptions = JSON.stringify(option);
}
});
if (pageList.length > 1 && pageList[pageList.length - 2]) {
const previousPage = pageList[pageList.length - 2];
postData.previousPage = previousPage.__route__;
postData.previousOptions = defaultOptions;
optionNameList.forEach((i) => {
const option = previousPage.data[i] || previousPage[i];
if (option) {
postData.previousOptions = JSON.stringify(option);
}
});
}
}
return postData;
}
export function mergeConfig(config0 = {}, config1 = {}) {
return {
...config0,
...config1,
};
}
export function combineUrl(url, host) {
return `${host.replace(/\/$/, '')}/${url.replace(/^\//, '')}`;
}
export function ifReqSuccess(res) {
return /^2/.test(res.statusCode.toString()) && res.data.errcode === 0;
}
export function ifReqNeedAuth(res) {
return res.data.errcode === 100 || res.data.errcode === 101;
}
export function handleError(res) {
if (res && res.data && res.data.msg) {
wx.showToast({
title: res.data.msg,
icon: 'none',
});
}
}
export default function wxRequest(config) {
return new Promise((resolve, reject) => {
wx.request({
...config,
success(res) {
const {
resolveWrap,
rejectWrap,
transformResponse,
validateStatus,
} = config;
if ((validateStatus && validateStatus(res)) || ifSuccess(res)) {
// eslint-disable-next-line no-underscore-dangle
const _resolve = resolveWrap ? resolveWrap(res) : res;
return resolve(transformResponse ? transformResponse(_resolve) : _resolve);
}
return reject(rejectWrap ? rejectWrap(res) : res);
},
fail(res) {
const { rejectWrap } = config;
reject(rejectWrap ? rejectWrap(res) : res);
},
});
});
}
function ifSuccess(res) {
return /^2/.test(res.statusCode.toString()) && res.data.errcode === 0;
}
......@@ -18,6 +18,31 @@ const formatNumber = n => {
return n[1] ? n : "0" + n;
};
function beforeFn(fn, inject) {
return (...args) => {
try {
inject(...args);
fn.call(this, ...args);
} catch (error) {
console.warn(error);
fn.call(this, ...args);
}
};
}
function afterFn(fn, inject) {
return (...args) => {
try {
fn.call(this, ...args);
inject(...args);
} catch (error) {
console.warn(error);
fn.call(this, ...args);
}
};
}
module.exports = {
formatTime: formatTime
formatTime,
beforeFn,
afterFn
};
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment