This commit is contained in:
quantulr
2023-08-30 17:27:21 +08:00
commit 0288146b0d
85 changed files with 26508 additions and 0 deletions

31
.eslintrc.js Normal file
View File

@ -0,0 +1,31 @@
/*
* Eslint config file
* Documentation: https://eslint.org/docs/user-guide/configuring/
* Install the Eslint extension before using this feature.
*/
module.exports = {
env: {
es6: true,
browser: true,
node: true,
},
ecmaFeatures: {
modules: true,
},
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
},
globals: {
wx: true,
App: true,
Page: true,
getCurrentPages: true,
getApp: true,
Component: true,
requirePlugin: true,
requireMiniProgram: true,
},
// extends: 'eslint:recommended',
rules: {},
}

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
node_modules/
miniprogram_npm/
package-lock.json

6
miniprogram/api/dict.ts Normal file
View File

@ -0,0 +1,6 @@
import httpClient from "../utils/request";
export const getDict = (dictType: string) =>
httpClient.request({
url: `/mini-app/dict/type/${dictType}`,
});

7
miniprogram/api/file.ts Normal file
View File

@ -0,0 +1,7 @@
import httpClient from "../utils/request";
export const uploadFile = (file: any) =>
httpClient.uploadFile({
url: "/file/upload",
file,
});

View File

@ -0,0 +1,57 @@
import httpClient from "../utils/request";
interface AddFinanceForm {
date?: string;
type?: string;
event?: string;
amount?: number;
oppositeCompany?: string;
}
export const addFinance = (data: AddFinanceForm) =>
httpClient.request({
url: "/mini-app/finance/detail",
method: "POST",
data,
});
interface QueryParams {
oppositeCompany?: string;
pageSize: number;
pageNum: number;
}
export const getFinanceList = (params: QueryParams) =>
httpClient.request({
url: "/mini-app/finance/detail/list",
params,
});
export const getFinanceInfo = (financeId: string) =>
httpClient.request({
url: `/mini-app/finance/detail/${financeId}`,
});
interface UpdateFinanceForm {
financeId?: string;
date?: string;
type?: string;
event?: string;
amount?: number;
oppositeCompany?: string;
}
export const updateFinance = (data: UpdateFinanceForm) =>
httpClient.request({
url: "/mini-app/finance/detail",
method: "PUT",
data,
});
export const deleteFinance = (financeIds: string) =>
httpClient.request({
url: `/mini-app/finance/detail/${financeIds}`,
method: "DELETE",
});
export const getStatistics = () =>
httpClient.request({
url: "/mini-app/finance/detail/statistics",
});

17
miniprogram/api/login.ts Normal file
View File

@ -0,0 +1,17 @@
import httpClient from "../utils/request";
interface LoginForm {
code: string;
}
export const login = (data: LoginForm) =>
httpClient.request({
url: "/mini-app/login",
method: "POST",
data,
});
export const getInfo = () =>
httpClient.request({
url: "/getInfo",
});

42
miniprogram/api/stock.ts Normal file
View File

@ -0,0 +1,42 @@
import httpClient from "../utils/request";
export const productList = () =>
httpClient.request({
url: "/mini-app/product/product-list",
});
export const modelList = (params: any) =>
httpClient.request({
url: `/mini-app/product/model-list`,
params,
});
export const specList = (params: any) =>
httpClient.request({
url: "/mini-app/product/spec-list",
params,
});
export const addStockLog = (data: any) =>
httpClient.request({
url: "/mini-app/product/stock-log",
method: "POST",
data,
});
export const stockLogList = (params: any) =>
httpClient.request({
url: "/mini-app/product/stock-log/list",
params,
});
export const storageList = (params: any) =>
httpClient.request({
url: "/mini-app/product/stock/list",
params,
});
export const stockStatistics = () =>
httpClient.request({
url: "/mini-app/product/stock/statistics",
});

49
miniprogram/app.json Normal file
View File

@ -0,0 +1,49 @@
{
"pages": [
"pages/index/index",
"pages/logs/logs",
"pages/add-finance/add-finance",
"pages/login/login",
"pages/stock/stock",
"pages/add-stock/add-stock"
],
"tabBar": {
"selectedColor": "#0052d9",
"list": [{
"pagePath": "pages/index/index",
"text": "财务",
"iconPath": "assets/tab-icons/money-collect.png",
"selectedIconPath": "assets/tab-icons/money-collect_selected.png"
},
{
"pagePath": "pages/stock/stock",
"text": "库存",
"iconPath": "assets/tab-icons/stock.png",
"selectedIconPath": "assets/tab-icons/stock_selected.png"
},
{
"pagePath": "pages/login/login",
"text": "我的",
"iconPath": "assets/tab-icons/sign-in.png",
"selectedIconPath": "assets/tab-icons/sign-in_selected.png"
}
]
},
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#f6f6f6",
"navigationBarTitleText": "口袋九章",
"navigationBarTextStyle": "black"
},
"usingComponents": {
"t-cell": "tdesign-miniprogram/cell/cell",
"t-icon": "tdesign-miniprogram/icon/icon",
"t-tabs": "tdesign-miniprogram/tabs/tabs",
"t-image": "tdesign-miniprogram/image/image",
"t-button": "tdesign-miniprogram/button/button",
"t-message": "tdesign-miniprogram/message/message",
"t-tab-panel": "tdesign-miniprogram/tab-panel/tab-panel",
"t-cell-group": "tdesign-miniprogram/cell-group/cell-group"
},
"sitemapLocation": "sitemap.json"
}

14
miniprogram/app.scss Normal file
View File

@ -0,0 +1,14 @@
/**app.wxss**/
.container {
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
padding: 200rpx 0;
box-sizing: border-box;
}
page {
background-color: #f6f6f6;
}

23
miniprogram/app.ts Normal file
View File

@ -0,0 +1,23 @@
import { getToken } from "./utils/settings";
// app.ts
App<IAppOption>({
globalData: {
authToken: undefined,
permissions:[]
},
onLaunch() {
// 展示本地存储能力
const logs = wx.getStorageSync("logs") || [];
logs.unshift(Date.now());
wx.setStorageSync("logs", logs);
this.globalData.authToken = getToken();
// 登录
wx.login({
success: (res) => {
console.log(res.code);
// 发送 res.code 到后台换取 openId, sessionKey, unionId
},
});
},
});

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 849 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 856 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 987 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -0,0 +1,4 @@
{
"component": true,
"usingComponents": {}
}

View File

@ -0,0 +1 @@
/* components/infinite-scroll/index.wxss */

View File

@ -0,0 +1,44 @@
// components/infinite-scroll/index.ts
Component({
/**
* 组件的属性列表
*/
properties: {},
/**
* 组件的初始数据
*/
data: {},
/**
* 组件的方法列表
*/
methods: {},
lifetimes: {
attached() {
//@ts-ignore
this._observer = wx.createIntersectionObserver(this);
//@ts-ignore
this._observer
// .createIntersectionObserver()
.relativeToViewport({ bottom: 100 })
.observe(".load-more", (res: any) => {
console.log(res);
res.intersectionRatio; // 相交区域占目标节点的布局区域的比例
res.intersectionRect; // 相交区域
res.intersectionRect.left; // 相交区域的左边界坐标
res.intersectionRect.top; // 相交区域的上边界坐标
res.intersectionRect.width; // 相交区域的宽度
res.intersectionRect.height; // 相交区域的高度
});
// //@ts-ignore
// this._observer = wx.createIntersectionObserver(this);
// //@ts-ignore
// this._observer.relativeTo(".scroll-view").observe(".load-more", (res) => {
// console.log("到底了");
// this.triggerEvent("loadmore", {}, {});
// });
},
},
});

View File

@ -0,0 +1,5 @@
<!--components/infinite-scroll/index.wxml-->
<view>
<slot></slot>
<view class="load-more">load more</view>
</view>

View File

@ -0,0 +1,4 @@
{
"component": true,
"usingComponents": {}
}

View File

@ -0,0 +1,28 @@
/* components/statistics-card/index.wxss */
.statistcs-card {
display: flex;
justify-content: space-between;
border-radius: 16rpx;
margin: 0 32rpx;
background-color: #fff;
padding: 32rpx 0;
.statistcs-item {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
&:not(:last-child) {
border-right: 1px solid #eee;
}
.value {
color: #0052d9;
font-size: larger;
font-weight: bold;
}
.title {
margin-top: 6rpx;
color: #555;
font-size: small;
}
}
}

View File

@ -0,0 +1,21 @@
// components/statistics-card/index.ts
Component({
/**
* 组件的属性列表
*/
properties: {
statisticsData: {
type: Object,
},
},
/**
* 组件的初始数据
*/
data: {},
/**
* 组件的方法列表
*/
methods: {},
});

View File

@ -0,0 +1,7 @@
<!--components/statistics-card/index.wxml-->
<view class="statistcs-card">
<view wx:for="{{statisticsData}}" wx:key="key" wx:for-item="value" class="statistcs-item">
<view class="value">{{value.value}}</view>
<view class="title">{{value.label}}</view>
</view>
</view>

View File

@ -0,0 +1,22 @@
export default [
{
icon: "home",
label: "首页",
url: "/pages/index/index",
},
{
icon: "card",
label: "分类",
url: "/pages/login/login",
},
{
icon: "home",
label: "购物车",
url: "/pages/cart/index",
},
{
icon: "cart",
label: "个人中心",
url: "pages/usercenter/index",
},
];

View File

@ -0,0 +1,8 @@
{
"component": true,
"usingComponents": {
"t-tab-bar": "tdesign-miniprogram/tab-bar/tab-bar",
"t-tab-bar-item": "tdesign-miniprogram/tab-bar-item/tab-bar-item",
"t-icon": "tdesign-miniprogram/icon/icon"
}
}

View File

@ -0,0 +1 @@
/* custom-tab-bar/index.wxss */

View File

@ -0,0 +1,28 @@
// custom-tab-bar/index.ts
import tabMenu from "./data";
Component({
/**
* 组件的属性列表
*/
properties: {},
/**
* 组件的初始数据
*/
data: {
active: 0,
list: tabMenu,
},
/**
* 组件的方法列表
*/
methods: {
onChange(e: any) {
console.log(e);
},
},
lifetimes: {
attached() {},
},
});

View File

@ -0,0 +1,6 @@
<!--custom-tab-bar/index.wxml-->
<t-tab-bar value="{{active}}" bindchange="onChange" theme="tag" split="{{false}}">
<t-tab-bar-item wx:for="{{list}}" wx:key="index" icon="{{item.icon}}" ariaLabel="{{item.ariaLabel}}">
{{item.label}}
</t-tab-bar-item>
</t-tab-bar>

15
miniprogram/package.json Normal file
View File

@ -0,0 +1,15 @@
{
"name": "miniprogram",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"tdesign-miniprogram": "^1.2.0"
}
}

View File

@ -0,0 +1,8 @@
{
"usingComponents": {
"t-input": "tdesign-miniprogram/input/input",
"t-date-time-picker": "tdesign-miniprogram/date-time-picker/date-time-picker",
"t-picker": "tdesign-miniprogram/picker/picker",
"t-picker-item": "tdesign-miniprogram/picker-item/picker-item"
}
}

View File

@ -0,0 +1,15 @@
/* pages/add-affairs/add-affairs.wxss */
.add-affairs {
padding-top: 32rpx;
.add-affairs-form {
border-radius: 18rpx;
overflow: hidden;
margin: 0 32rpx;
.t-input {
--td-input-label-min-width: 130rpx;
}
}
.submit-button {
margin: 32rpx 32rpx 0;
}
}

View File

@ -0,0 +1,247 @@
import Message from "tdesign-miniprogram/message/index";
import { getDict } from "../../api/dict";
import { addFinance, getFinanceInfo, updateFinance } from "../../api/finance";
// pages/add-affairs/add-affairs.ts
const dayjs = require("dayjs");
Page({
/**
* 页面的初始数据
*/
data: {
defaultTime: dayjs(dayjs().format("YYYY-MM-DD")).valueOf(),
types: [],
form: {
financeId: undefined,
event: undefined, //事务
type: undefined, // 类别
date: undefined, // 时间
oppositeCompany: undefined, // 对方账户
amount: undefined, // 金额
},
dateVisible: false,
pickerVisible: false,
},
onChange(e: any) {
const field = e.currentTarget.dataset.field;
this.setData({
[`form.${field}`]: e.detail.value,
});
},
showTypePicker() {
this.setData({
pickerVisible: true,
});
},
hidePicker() {
this.setData({
pickerVisible: false,
});
},
// 显示时间选择
showTimePicker() {
this.setData({
dateVisible: true,
});
},
hideTimePicker() {
this.setData({
dateVisible: false,
});
},
handleConfirmTime(e: any) {
console.log(e);
this.setData({
[`form.date`]: e.detail.value,
});
},
getTypeLabel(dictValue: string) {
// @ts-ignore
return this.data.types.find((item: any) => item.value === dictValue)?.label;
},
validate() {
const { form } = this.data;
const rules = {
event: [
{
required: true,
message: "请输入事项",
},
],
type: [
{
required: true,
message: "请选择类别",
},
],
date: [
{
required: true,
message: "请选择日期",
},
],
oppositeCompany: [
{
required: true,
message: "请输入对方账户",
},
],
amount: [
{
required: true,
message: "请输入金额",
},
],
};
for (const field of Object.keys(rules)) {
// @ts-ignore
for (const validation of rules[field]) {
if (validation.required) {
// @ts-ignore
if (typeof form[field] === "array") {
// @ts-ignore
if (form[field].length <= 0) {
return validation.message;
// throw new Error(validation.message);
}
} else {
// @ts-ignore
if (!form[field]) {
return validation.message;
// throw new Error(validation.message);
}
}
}
}
}
},
handleSubmitFinance() {
const { form } = this.data;
const result = this.validate();
if (result) {
Message.error({
context: this,
offset: [20, 32],
duration: 1000,
content: result,
});
return;
}
if (form.financeId) {
// 修改
updateFinance({
...form,
//@ts-ignore
type: form.type[0],
}).then(() => {
const pages = getCurrentPages();
const prevPage = pages[pages.length - 2];
prevPage.handleRefresh();
Message.success({
context: this,
offset: [20, 32],
duration: 3000,
content: "修改成功",
});
setTimeout(() => {
wx.switchTab({
url: "/pages/index/index",
});
}, 500);
});
} else {
// 新增
addFinance({
...form,
//@ts-ignore
type: form.type[0],
}).then(() => {
const pages = getCurrentPages();
const prevPage = pages[pages.length - 2];
prevPage.handleRefresh();
Message.success({
// context: this,
offset: [20, 32],
duration: 3000,
content: "新增成功",
});
setTimeout(() => {
wx.switchTab({
url: "/pages/index/index",
});
}, 500);
});
}
},
onPickerChange(e: any) {
this.setData({
["form.type"]: e.detail.value,
["form.typeLabel"]: e.detail.label,
});
},
getTypeOptions() {
getDict("finance_type").then((resp: any) => {
const options =
resp.data?.map((el: any) => ({
label: el.dictLabel,
value: el.dictValue,
})) ?? [];
this.setData({
types: options,
});
});
},
getFinanceDetail(financeId: string) {
getFinanceInfo(financeId).then((resp: any) => {
this.setData({
form: { ...resp.data, type: [resp.data.type] },
});
});
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(option: any) {
if (option.financeId) {
this.getFinanceDetail(option.financeId);
}
this.getTypeOptions();
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {},
/**
* 生命周期函数--监听页面显示
*/
onShow() {},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {},
});

View File

@ -0,0 +1,24 @@
<!--pages/add-affairs/add-affairs.wxml-->
<t-message id="t-message" />
<wxs module="times" src="../../utils/time.wxs" />
<wxs module="dict" src="../../utils/dict.wxs" />
<view class="add-affairs">
<view class="add-affairs-form">
<t-input label="事项" bind:change="onChange" data-field="event" value="{{form.event}}" align="right" placeholder="请输入事项"></t-input>
<t-cell title="选择类别" hover note="{{dict.getDictLabel(form.type[0], types) || ''}}" arrow data-mode="type" bindtap="showTypePicker" class="test" t-class="panel-item" />
<t-cell title="选择日期" hover note="{{times.formatDate(form.date) || ''}}" arrow data-mode="date" bindtap="showTimePicker" class="test" t-class="panel-item" />
<t-input label="对方账户" bind:change="onChange" data-field="oppositeCompany" value="{{form.oppositeCompany}}" align="right" placeholder="请输入对方账户"></t-input>
<t-input label="金额" type="number" bind:change="onChange" data-field="amount" value="{{form.amount}}" align="right" placeholder="请输入金额"></t-input>
</view>
<view class="submit-button">
<t-button bind:tap="handleSubmitFinance" theme="primary" block>确认提交</t-button>
</view>
<!-- 年月日 -->
<t-date-time-picker title="选择日期" visible="{{dateVisible}}" mode="date" defaultValue="{{form.date || defaultTime}}" format="YYYY-MM-DD HH:mm:ss" bindchange="handleConfirmTime" bindcancel="hideTimePicker" />
<t-picker visible="{{pickerVisible}}" value="{{form.type}}" data-key="type" title="选择类别" cancelBtn="取消" confirmBtn="确认" bindchange="onPickerChange" bindpick="onColumnChange" bindcancel="onPickerCancel">
<t-picker-item options="{{types}}" />
</t-picker>
</view>

View File

@ -0,0 +1,12 @@
{
"usingComponents": {
"t-popup": "tdesign-miniprogram/popup/popup",
"t-input": "tdesign-miniprogram/input/input",
"t-upload": "tdesign-miniprogram/upload/upload",
"t-picker": "tdesign-miniprogram/picker/picker",
"t-cascader": "tdesign-miniprogram/cascader/cascader",
"t-tree-select": "tdesign-miniprogram/tree-select/tree-select",
"t-picker-item": "tdesign-miniprogram/picker-item/picker-item",
"t-date-time-picker": "tdesign-miniprogram/date-time-picker/date-time-picker"
}
}

View File

@ -0,0 +1,24 @@
/* pages/add-stock/add-stock.wxss */
.add-stock {
padding: 32rpx 0;
.add-stock-form {
border-radius: 18rpx;
overflow: hidden;
margin: 0 32rpx;
.upload-wrapper {
padding: 32rpx 32rpx;
background-color: #fff;
.label {
font-size: 32rpx;
line-height: 44rpx;
padding-bottom: 16rpx;
}
.body {
margin-top: 24rpx;
}
}
}
.submit-button {
margin: 32rpx 32rpx 0;
}
}

View File

@ -0,0 +1,378 @@
// pages/add-stock/add-stock.ts
// const geneTree = async () => {
// return [...Array(10).keys()].map((el) => ({
// value: el,
// label: el,
// }));
import Message from "tdesign-miniprogram/message/index";
import { uploadFile } from "../../api/file";
import { addStockLog, modelList, productList, specList } from "../../api/stock";
import httpClient from "../../utils/request";
const dayjs = require("dayjs");
// };
Page({
/**
* 页面的初始数据
*/
data: {
prodPicList: [],
totalErrMsg: "",
defaultTime: dayjs(dayjs().format("YYYY-MM-DD")).valueOf(),
specPickerVisible: false,
productPickerVisible: false,
modelPickerVisible: false,
typePickerVisible: false,
dateVisible: false,
stockLimit: 0,
picList: [],
productOptions: [
{
label: "323q",
value: "313213",
children: [],
},
],
modelOptions: [],
specOptions: [],
types: [
{
label: "入库",
value: "1",
},
{
label: "出库",
value: "2",
},
],
form: {
type: undefined,
productId: undefined,
modelId: undefined,
specId: undefined,
picList: [],
total: undefined,
date: dayjs(dayjs().format("YYYY-MM-DD")).format("YYYY-MM-DD HH:mm:ss"),
},
pickerSubTitles: ["选择产品", "选择型号", "选择规格"],
},
onPick(e: any) {
console.log(e);
this.setData({
["productOptions[0].children"]: {
value: "fdsf",
label: "sdfa",
},
});
},
onChange(e: any) {
const field = e.currentTarget.dataset.field;
this.setData({
[`form.${field}`]: e.detail.value,
});
if (field === "total") {
if (
parseInt(e.detail.value) > this.data.stockLimit &&
this.data.form.type == 2
) {
this.setData({
// @ts-ignore
totalErrMsg: `出库数量不能大于库存数 : ` + this.data.stockLimit,
});
} else {
this.setData({
// @ts-ignore
totalErrMsg: "",
});
}
}
},
onPickerChange(e: any) {
console.log(e.detail);
const field = e.currentTarget.dataset.field;
this.setData({
[`form.${field}`]: e.detail.value[0],
});
if (field === "productId") {
// load model options
modelList({
productId: this.data.form.productId,
}).then((resp: any) => {
this.setData({
modelOptions: resp.rows.map((el: any) => ({
label: el.name,
value: el.modelId,
})),
});
});
} else if (field === "modelId") {
// load spec options
specList({
modelId: this.data.form.modelId,
}).then((resp: any) => {
this.setData({
specOptions: resp.rows.map((el: any) => ({
...el,
label: el.name,
value: el.specId,
})),
});
});
} else if (field === "specId") {
const spec: any = this.data.specOptions.find(
(el: any) => el.value == e.detail.value[0]
);
console.log(spec);
this.setData({
stockLimit: spec?.stock ?? 0,
prodPicList:
spec?.pic?.split(",")?.map((el: string) => {
let url;
if (el.startsWith("https://") || el.startsWith("http://")) {
url = el;
} else {
url = `${httpClient.baseUrl}${el}`;
}
return {
url,
};
}) ?? [],
});
}
},
onPickerCancel(e: any) {
console.log(e);
},
showPicker(e: any) {
const { pickerKey } = e.currentTarget.dataset;
this.setData({
[`${pickerKey}`]: true,
});
},
loadProductionOptions() {
productList().then((resp: any) => {
this.setData({
productOptions: resp.rows.map((el: any) => ({
label: el.name,
value: el.productId,
})),
});
});
},
handleAdd(e: any) {
const { picList } = this.data;
const { files } = e.detail;
this.setData({
// @ts-ignore
picList: [
...picList,
...files.map((el: any) => ({ ...el, status: "loading" })),
],
});
// uploadFile(files[0]);
for (const file of files) {
uploadFile(file)
.then((resp: any) => {
const { picList } = this.data;
const index = picList.findIndex((el: any) => el.url === file.url);
if (index != -1) {
this.setData({
[`picList[${index}].url`]: `${httpClient.baseUrl}${resp.url}`,
[`picList[${index}].percent`]: 100,
[`picList[${index}].status`]: null,
});
}
})
.catch(() => {
const { picList } = this.data;
const index = picList.findIndex((el: any) => el.url === file.url);
if (index != -1) {
picList.splice(index, 1);
this.setData({
picList,
});
}
});
}
},
hidePicker() {
this.setData({
dateVisible: false,
});
},
handleRemove(e: any) {
const { index } = e.detail;
const { picList } = this.data;
picList.splice(index, 1);
this.setData({
picList,
});
},
/**
* 生命周期函数--监听页面加载
*/
onLoad(option: any) {
if (option.type) {
this.setData({
["form.type"]: option.type,
});
this.loadProductionOptions();
} else {
wx.navigateBack();
}
},
validate() {
const { form } = this.data;
const rules = {
specId: [
{
required: true,
message: "请选择规格",
},
],
type: [
{
required: true,
message: "请选择类别",
},
],
date: [
{
required: true,
message: "请选择日期",
},
],
total: [
{
required: true,
message: "请输入数量",
},
{
validation: () => {
const { total } = this.data.form;
if (this.data.form.type == 2) {
// @ts-ignore
return total > this.data.stockLimit;
} else {
return false;
}
},
message: "出库数量不能超过总库存",
},
],
provePic: [
{
validation: () => {
return this.data.picList.length == 0;
},
message: "请上传凭证照片",
},
],
};
for (const field of Object.keys(rules)) {
// @ts-ignore
for (const validation of rules[field]) {
if (validation.validation) {
console.log(validation.validation());
if (validation.validation()) {
return validation.message;
}
}
if (validation.required) {
// @ts-ignore
if (typeof form[field] === "array") {
// @ts-ignore
if (form[field].length <= 0) {
return validation.message;
// throw new Error(validation.message);
}
} else {
// @ts-ignore
if (!form[field]) {
return validation.message;
// throw new Error(validation.message);
}
}
}
}
}
},
handleSubmitStock() {
let message;
message = this.validate();
if (message) {
Message.error({
context: this,
offset: [20, 32],
duration: 1000,
content: message,
});
return;
}
const { form } = this.data;
addStockLog({
specId: form.specId,
total: form.total,
date: form.date,
provePic: this.data.picList.map((el: any) => el.url).join(","),
type: form.type,
}).then(() => {
const pages = getCurrentPages();
const prevPage = pages[pages.length - 2];
prevPage.handleRefresh();
Message.success({
context: this,
offset: [20, 32],
duration: 3000,
content: "修改成功",
});
setTimeout(() => {
wx.switchTab({
url: "/pages/stock/stock",
});
}, 500);
});
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {},
/**
* 生命周期函数--监听页面显示
*/
onShow() {},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {},
});

View File

@ -0,0 +1,51 @@
<!--pages/add-stock/add-stock.wxml-->
<wxs module="dict" src="../../utils/dict.wxs" />
<wxs module="times" src="../../utils/time.wxs" />
<t-message id="t-message" />
<view class="add-stock">
<view class="add-stock-form">
<t-cell title="产品" note="{{dict.getDictLabel(form.productId, productOptions)}}" data-picker-key="productPickerVisible" bind:click="showPicker" arrow />
<t-cell title="型号" note="{{dict.getDictLabel(form.modelId, modelOptions)}}" data-picker-key="modelPickerVisible" bind:click="showPicker" arrow />
<t-cell title="规格" note="{{dict.getDictLabel(form.specId, specOptions)}}" data-picker-key="specPickerVisible" bind:click="showPicker" arrow />
<view class="upload-wrapper" wx:if="{{form.specId}}">
<text class="label">产品图片</text>
<view class="body">
<view class="prod-image-list">
<t-image wx:for="{{prodPicList}}" wx:key="url" shape="round" width="150rpx" height="150rpx" src="{{item.url}}"></t-image>
</view>
</view>
</view>
<t-cell title="类型" note="{{dict.getDictLabel(form.type, types)}}" data-picker-key="typePickerVisible" bind:click="showPicker" arrow />
<t-cell title="选择日期" hover note="{{times.formatDate(form.date) || ''}}" arrow data-mode="date" data-picker-key="dateVisible" bindtap="showPicker" class="test" t-class="panel-item" />
<view class="upload-wrapper">
<text class="label">凭证照片</text>
<view class="body">
<t-upload class="upload" mediaType="{{['image']}}" files="{{picList}}" bind:add="handleAdd" bind:remove="handleRemove">
</t-upload>
</view>
</view>
<t-input label="数量" type="number" bind:change="onChange" data-field="total" value="{{form.total}}" placeholder="请输入数量" tips="{{totalErrMsg}}" status="{{totalErrMsg?'error':''}}" />
</view>
<view class="submit-button">
<t-button bind:tap="handleSubmitStock" theme="primary" block>确认提交</t-button>
</view>
<!-- 产品选择器 -->
<t-picker default-value="{{[form.productId]}}" visible="{{productPickerVisible}}" value="{{form.productId}}" data-key="productId" data-field="productId" title="选择产品" cancelBtn="取消" confirmBtn="确认" bindchange="onPickerChange" bindcancel="onPickerCancel">
<t-picker-item options="{{productOptions}}" />
</t-picker>
<!-- 型号选择器 -->
<t-picker default-value="{{[form.modelId]}}" visible="{{modelPickerVisible}}" value="{{form.modelId}}" data-key="modelId" data-field="modelId" title="选择型号" cancelBtn="取消" confirmBtn="确认" bindchange="onPickerChange" bindcancel="onPickerCancel">
<t-picker-item options="{{modelOptions}}" />
</t-picker>
<!-- 规格选择器 -->
<t-picker default-value="{{[form.specId]}}" visible="{{specPickerVisible}}" value="{{form.specId}}" data-key="specId" data-field="specId" title="选择规格" cancelBtn="取消" confirmBtn="确认" bindchange="onPickerChange" bindcancel="onPickerCancel">
<t-picker-item options="{{specOptions}}" />
</t-picker>
<!-- 类型选择器 -->
<t-picker default-value="{{[form.type]}}" visible="{{typePickerVisible}}" value="{{form.type}}" data-key="type" data-field="type" title="选择类别" cancelBtn="取消" confirmBtn="确认" bindchange="onPickerChange" bindcancel="onPickerCancel">
<t-picker-item options="{{types}}" />
</t-picker>
<!-- 日期 -->
<t-date-time-picker title="选择日期" visible="{{dateVisible}}" mode="date" data-field="date" defaultValue="{{form.date || defaultTime}}" format="YYYY-MM-DD HH:mm:ss" bindchange="onChange" bindcancel="hidePicker" />
</view>

View File

@ -0,0 +1,9 @@
{
"usingComponents": {
"t-fab": "tdesign-miniprogram/fab/fab",
"t-collapse": "tdesign-miniprogram/collapse/collapse",
"t-collapse-panel": "tdesign-miniprogram/collapse-panel/collapse-panel",
"statistics-card": "/components/statistics-card"
},
"enablePullDownRefresh": true
}

View File

@ -0,0 +1,118 @@
/* pages/index/index.wxss */
page {
padding: 32rpx 0;
background-color: #f6f6f6;
}
.home-page {
.t-fab {
z-index: 99;
}
.divider {
height: 1px;
background-color: #ccc;
margin: 36rpx 32rpx;
}
.list {
margin: 0 32rpx;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 32rpx;
.card {
box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
position: relative;
// aspect-ratio: 1/1;
min-height: 300rpx;
background-color: #fff;
border-radius: 18rpx;
padding: 18rpx;
.close-button {
position: absolute;
top: -24rpx;
right: -24rpx;
}
.field {
margin-top: 12rpx;
display: flex;
.indicator {
margin-top: 12rpx;
height: 24rpx;
width: 8rpx;
background-color: #ea7e41;
border-radius: 50rpx;
margin-right: 12rpx;
}
.content {
margin-top: 6rpx;
display: flex;
flex-direction: column;
.title {
font-size: large;
}
.value {
font-size: small;
}
}
&:nth-of-type(1) {
.indicator {
background-color: #ea7e41;
}
}
&:nth-of-type(2) {
.indicator {
background-color: #12b3a8;
}
}
&:nth-of-type(3) {
.indicator {
background-color: #dc7d85;
}
}
&:nth-of-type(4) {
.indicator {
background-color: #e0d2fd;
}
}
&:nth-of-type(5) {
.indicator {
background-color: #dc7d85;
}
}
}
}
.shake {
animation: shake-crazy 1s infinite linear;
}
}
.to-login {
height: 40vh;
display: flex;
justify-content: center;
align-items: center;
}
}
@keyframes shake-crazy {
0% {
transform: translate(0px, 0px) rotate(0deg);
}
17% {
transform: translate(0.2px, 0.2px) rotate(2deg);
}
34% {
transform: translate(-0.2px, -0.2px) rotate(-2deg);
}
51% {
transform: translate(0px, -0.3px) rotate(0deg);
}
68% {
transform: translate(0.2px, -0.2px) rotate(2deg);
}
85% {
transform: translate(-0.2px, 0.2px) rotate(-2deg);
}
100% {
transform: translate(0px, 0.3px) rotate(0deg);
}
}

View File

@ -0,0 +1,210 @@
import { getDict } from "../../api/dict";
import {
deleteFinance,
getFinanceList,
getStatistics,
} from "../../api/finance";
// pages/index/index.ts
Page({
/**
* 页面的初始数据
*/
data: {
queryParams: {
pageNum: 1,
pageSize: 10,
},
authToken: undefined,
statistics: {
amount: {
label: "账户余额",
value: 0,
},
income: {
label: "当月入账",
value: 0,
},
expenditure: {
label: "当月出账",
value: 0,
},
},
loading: false,
total: 0,
completed: false,
deleteIndex: -1,
list: [],
types: [],
},
async getList() {
this.setData({
loading: true,
});
const { queryParams } = this.data;
try {
const resp: any = await getFinanceList(queryParams);
let completed = false;
if (
Math.ceil(resp.total / this.data.queryParams.pageSize) ==
this.data.queryParams.pageNum
) {
completed = true;
}
this.setData({
completed,
total: resp.total,
list: resp.rows,
});
if (!completed) {
this.setData({
["queryParams.pageNum"]: this.data.queryParams.pageNum + 1,
});
}
} catch (e) {
console.log(e);
}
this.setData({
loading: false,
});
},
async getStatisticsDetail() {
const resp: any = await getStatistics();
this.setData({
['statistics.amount.value']: resp.data.amount,
['statistics.income.value']: resp.data.income,
['statistics.expenditure.value']: resp.data.expenditure,
});
},
handleAddAffairs() {
wx.navigateTo({
url: "/pages/add-finance/add-finance",
fail(err) {
console.log(err);
},
});
},
handleUpdateFinance(e: any) {
const financeId = e.currentTarget.dataset.financeId;
wx.navigateTo({
url: `/pages/add-finance/add-finance?financeId=${financeId}`,
});
},
getTypeOptions() {
getDict("finance_type").then((resp: any) => {
const options =
resp.data?.map((el: any) => ({
label: el.dictLabel,
value: el.dictValue,
})) ?? [];
this.setData({
types: options,
});
});
},
handleLongTap(e: any) {
console.log(e);
const { deleteIndex } = this.data;
const index = parseInt(e.currentTarget.dataset.index);
let resultIndex;
if (deleteIndex == index) {
resultIndex = -1;
} else {
resultIndex = index;
}
this.setData({
deleteIndex: resultIndex,
});
},
handleDeleteFinance(e: any) {
const { financeId } = e.currentTarget.dataset;
deleteFinance(financeId).then(() => {
const { list } = this.data;
this.setData({
list: list.filter((el: any) => el.financeId !== financeId),
deleteIndex: -1,
});
});
},
loadMore() {
const { loading, completed } = this.data;
if (loading || completed) {
return;
}
this.getList();
},
toLogin() {
wx.switchTab({
url: "/pages/login/login",
});
},
loadPageData() {
const authToken = getApp().globalData.authToken;
this.setData({
authToken,
});
if (!authToken) return;
this.getList();
this.getTypeOptions();
this.getStatisticsDetail();
},
/**
* 生命周期函数--监听页面加载
*/
onLoad() {},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
this.loadPageData();
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {},
async handleRefresh() {
this.setData({
["queryParams.pageNum"]: 1,
completed: false,
loading: false,
total: 0,
list: [],
});
await this.getList();
await this.getStatisticsDetail();
wx.stopPullDownRefresh();
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
this.handleRefresh();
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
console.log("reach bottom");
this.loadMore();
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {},
});

View File

@ -0,0 +1,52 @@
<!--pages/index/index.wxml-->
<t-message id="t-message" />
<wxs module="times" src="../../utils/time.wxs" />
<wxs module="dict" src="../../utils/dict.wxs" />
<view class="home-page">
<t-fab class="float-button" icon="add" aria-label="增加" bind:click="handleAddAffairs" />
<statistics-card statistics-data="{{statistics}}" />
<view class="divider"></view>
<view wx:if="{{authToken}}" class="list">
<view wx:for="{{list}}" wx:key="account" data-finance-id="{{item.financeId}}" bind:longpress="handleLongTap" data-index="{{index}}" bind:tap="handleUpdateFinance" class="{{ index === deleteIndex ? 'card shake' : 'card' }}">
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">事项</text>
<text class="value">{{item.event}}</text>
</view>
</view>
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">类别</text>
<text class="value">{{dict.getDictLabel(item.type, types)}}</text>
</view>
</view>
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">时间</text>
<text class="value">{{times.formatDate(item.date) || "-"}}</text>
</view>
</view>
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">对方账户</text>
<text class="value">{{item.oppositeCompany}}</text>
</view>
</view>
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">金额</text>
<text class="value">{{item.amount}}</text>
</view>
</view>
<t-icon wx:if="{{index === deleteIndex}}" name="close-circle-filled" color="red" size="56rpx" data-finance-id="{{item.financeId}}" data-index="{{index}}" catchtap="handleDeleteFinance" class="close-button"></t-icon>
</view>
</view>
<view wx:else class="to-login">
<t-button icon="login" theme="primary" bind:tap="toLogin">前往登录</t-button>
</view>
</view>

View File

@ -0,0 +1,3 @@
{
"usingComponents": {}
}

View File

@ -0,0 +1,11 @@
/* pages/login/login.wxss */
.login{
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
.login-button{
margin-top: 60rpx;
}
}

View File

@ -0,0 +1,74 @@
import { login } from "../../api/login";
import { setToken } from "../../utils/settings";
// pages/login/login.ts
Page({
/**
* 页面的初始数据
*/
data: {
authToken: undefined,
},
loginWithWeChat(e: any) {
login({
code: e.detail.code,
}).then((response: any) => {
setToken(response.token);
// setToken(response.token);
wx.switchTab({
url: "/pages/index/index",
});
});
},
handleLogout(){
this.setData({
authToken: undefined
})
setToken(undefined)
},
/**
* 生命周期函数--监听页面加载
*/
onLoad() {
const authToken = getApp().globalData.authToken;
this.setData({
authToken,
});
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {},
/**
* 生命周期函数--监听页面显示
*/
onShow() {},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {},
});

View File

@ -0,0 +1,7 @@
<!--pages/login/login.wxml-->
<t-message id="t-message" />
<view class="login">
<t-icon name="user-arrow-up" size="72rpx" color="#0052d9"></t-icon>
<t-button wx:if="{{authToken}}" class="login-button" shape="round" theme="primary">退出登录</t-button>
<t-button wx:else class="login-button" shape="round" open-type="getPhoneNumber" bindgetphonenumber="loginWithWeChat" theme="primary">手机号快捷登录</t-button>
</view>

View File

@ -0,0 +1,6 @@
{
"navigationBarTitleText": "查看启动日志",
"usingComponents": {
"t-divider": "tdesign-miniprogram/divider/divider"
}
}

View File

@ -0,0 +1 @@
/* pages/logs/logs.wxss */

View File

@ -0,0 +1,19 @@
// logs.ts
// const util = require('../../utils/util.js')
import { formatTime } from '../../utils/util'
Page({
data: {
logs: [],
},
onLoad() {
this.setData({
logs: (wx.getStorageSync('logs') || []).map((log: string) => {
return {
date: formatTime(new Date(log)),
timeStamp: log
}
}),
})
},
})

View File

@ -0,0 +1,6 @@
<!--logs.wxml-->
<view class="container log-list">
<block wx:for="{{logs}}" wx:key="timeStamp" wx:for-item="log">
<text class="log-item">{{index + 1}}. {{log.date}}</text>
</block>
</view>

View File

@ -0,0 +1,8 @@
.log-list {
display: flex;
flex-direction: column;
padding: 40rpx;
}
.log-item {
margin: 10rpx;
}

View File

@ -0,0 +1,3 @@
{
"usingComponents": {}
}

View File

@ -0,0 +1 @@
/* pages/product/product.wxss */

View File

@ -0,0 +1,66 @@
// pages/product/product.ts
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad() {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {
}
})

View File

@ -0,0 +1,3 @@
<!--pages/product/product.wxml-->
<!-- <text>pages/product/product.wxml</text> -->
<view></view>

View File

@ -0,0 +1,7 @@
{
"usingComponents": {
"t-fab": "tdesign-miniprogram/fab/fab",
"statistics-card": "/components/statistics-card"
},
"enablePullDownRefresh": true
}

View File

@ -0,0 +1,92 @@
/* pages/stock/stock.wxss */
.t-fab {
z-index: 99;
}
page{
padding-top: 32rpx;
}
.stock-tabs {
margin: 16rpx 32rpx 0;
}
.stock-list {
padding: 16rpx 0 32rpx;
.scroll-container {
// height: calc(100vh - 96rpx - 64rpx - 64rpx);
.grid {
margin: 0 32rpx;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 32rpx;
.card {
box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1),
0 1px 2px -1px rgb(0 0 0 / 0.1);
// position: relative;
min-height: 300rpx;
background-color: #fff;
border-radius: 18rpx;
padding: 18rpx;
.prove-pic {
width: 100%;
height: 200rpx;
}
.close-button {
position: absolute;
top: -24rpx;
right: -24rpx;
}
.fields {
margin-top: 12rpx;
.field {
margin-top: 12rpx;
display: flex;
.indicator {
margin-top: 12rpx;
height: 24rpx;
width: 8rpx;
background-color: #ea7e41;
border-radius: 50rpx;
margin-right: 12rpx;
}
.content {
display: flex;
flex-direction: column;
.title {
font-size: large;
}
.value {
margin-top: 6rpx;
font-size: small;
}
}
&:nth-of-type(1) {
.indicator {
background-color: #ea7e41;
}
}
&:nth-of-type(2) {
.indicator {
background-color: #12b3a8;
}
}
&:nth-of-type(3) {
.indicator {
background-color: #dc7d85;
}
}
&:nth-of-type(4) {
.indicator {
background-color: #e0d2fd;
}
}
&:nth-of-type(5) {
.indicator {
background-color: #dc7d85;
}
}
}
}
}
}
}
}

View File

@ -0,0 +1,339 @@
import { stockLogList, stockStatistics, storageList } from "../../api/stock";
import httpClient from "../../utils/request";
// pages/stock/stock.ts
Page({
/**
* 页面的初始数据
*/
data: {
authToken: undefined,
stockType: 0, // 库存类型
// 统计数据
statisticsData: {
total: {
label: "产品总数",
value: 0,
},
in: {
label: "当月入库",
value: 0,
},
out: {
label: "当月出库",
value: 0,
},
},
inStockQuery: {
pageNum: 1,
pageSize: 10,
},
outStockQuery: {
pageNum: 1,
pageSize: 10,
},
storageQuery: {
pageNum: 1,
pageSize: 10,
},
storageList: [], // 库存列表
inStockList: [], // 入库列表
outStockList: [], // 出库列表
storageLoading: false,
inStockLoading: false,
outStockLoading: false,
storageCompleted: false,
inStockCompleted: false,
outStockCompleted: false,
},
onTabsChange(e: any) {
const { value: stockType } = e.detail;
this.setData({
stockType,
});
if (stockType > 0) {
if (
(stockType == 1 && this.data.inStockList.length == 0) ||
(stockType == 2 && this.data.outStockList.length == 0)
) {
this.getStockIOList();
}
} else {
if (this.data.storageList.length === 0) {
this.getStorageList();
}
}
},
async loadData() {
const authToken = getApp().globalData.authToken;
this.setData({
authToken,
});
if (!authToken) return;
const { stockType } = this.data;
if (stockType == 0) {
await this.getStorageList();
} else {
await this.getStockIOList();
}
await this.loadStatisticData();
},
/**
* 加载出入库日志列表
*/
async getStockIOList() {
const { inStockQuery, outStockQuery, stockType } = this.data;
let query;
if (stockType == 1) {
this.setData({
inStockLoading: true,
});
query = inStockQuery;
} else if (stockType == 2) {
this.setData({
outStockLoading: true,
});
query = outStockQuery;
} else {
return;
}
try {
const resp: any = await stockLogList({
type: stockType,
pageNum: query.pageNum,
pageSize: query.pageSize,
});
let completed = false;
if (stockType == 1) {
if (
Math.ceil(resp.total / inStockQuery.pageSize) == inStockQuery.pageNum
) {
completed = true;
}
this.setData({
inStockCompleted: completed,
// @ts-ignore
inStockList: [
...this.data.inStockList,
...resp.rows.map((el: any) => ({
...el,
provePic:
el.provePic?.split(",").map((img: string) => {
if (img.startsWith("http://") || img.startsWith("https://")) {
return img;
} else {
return `${httpClient.baseUrl}${img}`;
}
}) ?? [],
})),
],
});
if (!completed) {
this.setData({
["inStockQuery.pageNum"]: inStockQuery.pageNum + 1,
});
}
} else if (stockType == 2) {
if (
Math.ceil(resp.total / outStockQuery.pageSize) ==
outStockQuery.pageNum
) {
completed = true;
}
this.setData({
outStockCompleted: completed,
// @ts-ignore
outStockList: [
...this.data.outStockList,
...resp.rows.map((el: any) => ({
...el,
provePic:
el.provePic?.split(",").map((img: string) => {
if (img.startsWith("http://") || img.startsWith("https://")) {
return img;
} else {
return `${httpClient.baseUrl}${img}`;
}
}) ?? [],
})),
],
});
if (!completed) {
this.setData({
["outStockQuery.pageNum"]: outStockQuery.pageNum + 1,
});
}
}
} catch (error) {
console.log(error);
}
if (this.data.stockType == 1) {
this.setData({
inStockLoading: false,
});
} else if (this.data.stockType == 2) {
this.setData({
outStockLoading: false,
});
}
},
/**
* 获取库存列表
*/
async getStorageList() {
this.setData({
storageLoading: false,
});
const { storageQuery } = this.data;
try {
const resp: any = await storageList(storageQuery);
let completed = false;
if (
Math.ceil(resp.total / storageQuery.pageSize) == storageQuery.pageNum
) {
completed = true;
}
this.setData({
// @ts-ignore
storageList: [...this.data.storageList, ...resp.rows],
storageCompleted: completed,
});
if (!completed) {
this.setData({
[`storageQuery.pageNum`]: storageQuery.pageNum + 1,
});
}
} catch (error) {}
this.setData({
storageLoading: false,
});
},
/**
* 获取统计数据列表
*/
async loadStatisticData() {
const resp: any = await stockStatistics();
this.setData({
["statisticsData.in.value"]: resp.data.in,
["statisticsData.out.value"]: resp.data.out,
["statisticsData.total.value"]: resp.data.total,
});
},
/**
* 触底时,加载更多库存列表
*/
loadMoreStorage() {
console.log("库存到底了");
const { storageLoading, storageCompleted } = this.data;
if (storageLoading || storageCompleted) {
return;
}
this.getStorageList();
},
/**
* 触底时,加载更多入库列表
*/
loadMoreInStock() {
const { inStockLoading, inStockCompleted } = this.data;
console.log(inStockLoading, inStockCompleted);
if (inStockLoading || inStockCompleted) {
return;
}
this.getStockIOList();
},
/**
* 触底时,加载更多出库列表
*/
loadMoreOutStock() {
const { outStockLoading, outStockCompleted } = this.data;
if (outStockLoading || outStockCompleted) {
return;
}
this.getStockIOList();
},
handleAddStock() {
const { stockType } = this.data;
wx.navigateTo({
url: `/pages/add-stock/add-stock?type=${stockType}`,
});
},
handleUpdateStock() {},
/**
* 生命周期函数--监听页面加载
*/
onLoad() {
this.loadData();
},
/**
* 刷新此页面
*/
async handleRefresh() {
this.setData({
["inStockQuery.pageNum"]: 1,
["outStockQuery.pageNum"]: 1,
["storageQuery.pageNum"]: 1,
storageLoading: false,
inStockLoading: false,
outStockLoading: false,
storageCompleted: false,
inStockCompleted: false,
outStockCompleted: false,
inStockList: [],
outStockList: [],
storageList: [],
});
await this.loadData();
wx.stopPullDownRefresh();
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() {},
/**
* 生命周期函数--监听页面显示
*/
onShow() {},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() {
this.handleRefresh();
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() {
const { stockType } = this.data;
if (stockType == 0) {
this.loadMoreStorage();
} else if (stockType == 1) {
this.loadMoreInStock();
} else if (stockType == 2) {
this.loadMoreOutStock();
}
},
/**
* 用户点击右上角分享
*/
onShareAppMessage() {},
});

View File

@ -0,0 +1,140 @@
<!--pages/stock/stock.wxml-->
<!-- 产品库存管理 -->
<wxs module="times" src="../../utils/time.wxs" />
<statistics-card statistics-data="{{statisticsData}}" />
<t-tabs class="stock-tabs" defaultValue="{{0}}" value="{{stockType}}" bind:change="onTabsChange" theme="tag">
<t-tab-panel label="库存" value="{{0}}" />
<t-tab-panel label="入库" value="{{1}}" />
<t-tab-panel label="出库" value="{{2}}" />
</t-tabs>
<view class="stock-list">
<t-fab wx:if="{{stockType > 0}}" class="float-button" icon="add" aria-label="增加" bind:click="handleAddStock"></t-fab>
<view hidden="{{stockType!=0}}" class="scroll-container">
<view class="grid">
<view wx:for="{{storageList}}" wx:key="specId" class="card">
<view class="fields">
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">产品</text>
<text class="value">{{item.productName}}</text>
</view>
</view>
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">型号</text>
<text class="value">{{item.modelName}}</text>
</view>
</view>
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">规格</text>
<text class="value">{{item.specName}}</text>
</view>
</view>
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">库存</text>
<text class="value">{{item.stock}}</text>
</view>
</view>
</view>
</view>
</view>
</view>
<view hidden="{{stockType!=1}}" class="scroll-container">
<view class="grid">
<view wx:for="{{inStockList}}" wx:key="logId" class="card">
<t-image class="prove-pic" mode="aspectFill" error="slot" src="{{item.provePic[0]}}">
<t-icon name="image-error" slot="error" />
</t-image>
<view class="fields">
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">产品</text>
<text class="value">{{item.productName}}</text>
</view>
</view>
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">型号</text>
<text class="value">{{item.modelName}}</text>
</view>
</view>
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">规格</text>
<text class="value">{{item.specName}}</text>
</view>
</view>
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">数量</text>
<text class="value">{{item.total}}</text>
</view>
</view>
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">日期</text>
<text class="value">{{times.formatDate(item.date) || "-"}}</text>
</view>
</view>
</view>
</view>
</view>
</view>
<view hidden="{{stockType!=2}}" class="scroll-container">
<view class="grid">
<view wx:for="{{outStockList}}" wx:key="logId" class="card">
<t-image class="prove-pic" mode="aspectFill" error="slot" src="{{item.provePic[0]}}">
<t-icon name="image-error" slot="error" width="100rpx" height="100rpx" />
</t-image>
<view class="fields">
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">产品</text>
<text class="value">{{item.productName}}</text>
</view>
</view>
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">型号</text>
<text class="value">{{item.modelName}}</text>
</view>
</view>
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">规格</text>
<text class="value">{{item.specName}}</text>
</view>
</view>
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">数量</text>
<text class="value">{{item.total}}</text>
</view>
</view>
<view class="field">
<view class="indicator"></view>
<view class="content">
<text class="title">日期</text>
<text class="value">{{times.formatDate(item.date) || "-"}}</text>
</view>
</view>
</view>
</view>
</view>
</view>
</view>

7
miniprogram/sitemap.json Normal file
View File

@ -0,0 +1,7 @@
{
"desc": "关于本文件的更多信息,请参考文档 https://developers.weixin.qq.com/miniprogram/dev/framework/sitemap.html",
"rules": [{
"action": "allow",
"page": "*"
}]
}

View File

@ -0,0 +1,418 @@
/**
* 表单验证
*
* @param {Object} rules 验证字段的规则
* @param {Object} messages 验证字段的提示信息
*
*/
class WxValidate {
constructor(rules = {}, messages = {}) {
Object.assign(this, {
data: {},
rules,
messages,
})
this.__init()
}
/**
* __init
*/
__init() {
this.__initMethods()
this.__initDefaults()
this.__initData()
}
/**
* 初始化数据
*/
__initData() {
this.form = {}
this.errorList = []
}
/**
* 初始化默认提示信息
*/
__initDefaults() {
this.defaults = {
messages: {
required: '这是必填字段。',
email: '请输入有效的电子邮件地址。',
tel: '请输入11位的手机号码。',
url: '请输入有效的网址。',
date: '请输入有效的日期。',
dateISO: '请输入有效的日期ISO例如2009-06-231998/01/22。',
number: '请输入有效的数字。',
digits: '只能输入数字。',
idcard: '请输入18位的有效身份证。',
equalTo: this.formatTpl('输入值必须和 {0} 相同。'),
contains: this.formatTpl('输入值必须包含 {0}。'),
minlength: this.formatTpl('最少要输入 {0} 个字符。'),
maxlength: this.formatTpl('最多可以输入 {0} 个字符。'),
rangelength: this.formatTpl('请输入长度在 {0} 到 {1} 之间的字符。'),
min: this.formatTpl('请输入不小于 {0} 的数值。'),
max: this.formatTpl('请输入不大于 {0} 的数值。'),
range: this.formatTpl('请输入范围在 {0} 到 {1} 之间的数值。'),
}
}
}
/**
* 初始化默认验证方法
*/
__initMethods() {
const that = this
that.methods = {
/**
* 验证必填元素
*/
required(value, param) {
if (!that.depend(param)) {
return 'dependency-mismatch'
} else if (typeof value === 'number') {
value = value.toString()
} else if (typeof value === 'boolean') {
return !0
}
return value.length > 0
},
/**
* 验证电子邮箱格式
*/
email(value) {
return that.optional(value) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(value)
},
/**
* 验证手机格式
*/
tel(value) {
return that.optional(value) || /^1[34578]\d{9}$/.test(value)
},
/**
* 验证URL格式
*/
url(value) {
return that.optional(value) || /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(value)
},
/**
* 验证日期格式
*/
date(value) {
return that.optional(value) || !/Invalid|NaN/.test(new Date(value).toString())
},
/**
* 验证ISO类型的日期格式
*/
dateISO(value) {
return that.optional(value) || /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(value)
},
/**
* 验证十进制数字
*/
number(value) {
return that.optional(value) || /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value)
},
/**
* 验证整数
*/
digits(value) {
return that.optional(value) || /^\d+$/.test(value)
},
/**
* 验证身份证号码
*/
idcard(value) {
return that.optional(value) || /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(value)
},
/**
* 验证两个输入框的内容是否相同
*/
equalTo(value, param) {
return that.optional(value) || value === that.data[param]
},
/**
* 验证是否包含某个值
*/
contains(value, param) {
return that.optional(value) || value.indexOf(param) >= 0
},
/**
* 验证最小长度
*/
minlength(value, param) {
return that.optional(value) || value.length >= param
},
/**
* 验证最大长度
*/
maxlength(value, param) {
return that.optional(value) || value.length <= param
},
/**
* 验证一个长度范围[min, max]
*/
rangelength(value, param) {
return that.optional(value) || (value.length >= param[0] && value.length <= param[1])
},
/**
* 验证最小值
*/
min(value, param) {
return that.optional(value) || value >= param
},
/**
* 验证最大值
*/
max(value, param) {
return that.optional(value) || value <= param
},
/**
* 验证一个值范围[min, max]
*/
range(value, param) {
return that.optional(value) || (value >= param[0] && value <= param[1])
},
}
}
/**
* 添加自定义验证方法
* @param {String} name 方法名
* @param {Function} method 函数体,接收两个参数(value, param)value表示元素的值param表示参数
* @param {String} message 提示信息
*/
addMethod(name, method, message) {
this.methods[name] = method
this.defaults.messages[name] = message !== undefined ? message : this.defaults.messages[name]
}
/**
* 判断验证方法是否存在
*/
isValidMethod(value) {
let methods = []
for (let method in this.methods) {
if (method && typeof this.methods[method] === 'function') {
methods.push(method)
}
}
return methods.indexOf(value) !== -1
}
/**
* 格式化提示信息模板
*/
formatTpl(source, params) {
const that = this
if (arguments.length === 1) {
return function() {
let args = Array.from(arguments)
args.unshift(source)
return that.formatTpl.apply(this, args)
}
}
if (params === undefined) {
return source
}
if (arguments.length > 2 && params.constructor !== Array) {
params = Array.from(arguments).slice(1)
}
if (params.constructor !== Array) {
params = [params]
}
params.forEach(function(n, i) {
source = source.replace(new RegExp("\\{" + i + "\\}", "g"), function() {
return n
})
})
return source
}
/**
* 判断规则依赖是否存在
*/
depend(param) {
switch (typeof param) {
case 'boolean':
param = param
break
case 'string':
param = !!param.length
break
case 'function':
param = param()
default:
param = !0
}
return param
}
/**
* 判断输入值是否为空
*/
optional(value) {
return !this.methods.required(value) && 'dependency-mismatch'
}
/**
* 获取自定义字段的提示信息
* @param {String} param 字段名
* @param {Object} rule 规则
*/
customMessage(param, rule) {
const params = this.messages[param]
const isObject = typeof params === 'object'
if (params && isObject) return params[rule.method]
}
/**
* 获取某个指定字段的提示信息
* @param {String} param 字段名
* @param {Object} rule 规则
*/
defaultMessage(param, rule) {
let message = this.customMessage(param, rule) || this.defaults.messages[rule.method]
let type = typeof message
if (type === 'undefined') {
message = `Warning: No message defined for ${rule.method}.`
} else if (type === 'function') {
message = message.call(this, rule.parameters)
}
return message
}
/**
* 缓存错误信息
* @param {String} param 字段名
* @param {Object} rule 规则
* @param {String} value 元素的值
*/
formatTplAndAdd(param, rule, value) {
let msg = this.defaultMessage(param, rule)
this.errorList.push({
param: param,
msg: msg,
value: value,
})
}
/**
* 验证某个指定字段的规则
* @param {String} param 字段名
* @param {Object} rules 规则
* @param {Object} data 需要验证的数据对象
*/
checkParam(param, rules, data) {
// 缓存数据对象
this.data = data
// 缓存字段对应的值
const value = data[param] !== null && data[param] !== undefined ? data[param] : ''
// 遍历某个指定字段的所有规则,依次验证规则,否则缓存错误信息
for (let method in rules) {
// 判断验证方法是否存在
if (this.isValidMethod(method)) {
// 缓存规则的属性及值
const rule = {
method: method,
parameters: rules[method]
}
// 调用验证方法
const result = this.methods[method](value, rule.parameters)
// 若result返回值为dependency-mismatch则说明该字段的值为空或非必填字段
if (result === 'dependency-mismatch') {
continue
}
this.setValue(param, method, result, value)
// 判断是否通过验证,否则缓存错误信息,跳出循环
if (!result) {
this.formatTplAndAdd(param, rule, value)
break
}
}
}
}
/**
* 设置字段的默认验证值
* @param {String} param 字段名
*/
setView(param) {
this.form[param] = {
$name: param,
$valid: true,
$invalid: false,
$error: {},
$success: {},
$viewValue: ``,
}
}
/**
* 设置字段的验证值
* @param {String} param 字段名
* @param {String} method 字段的方法
* @param {Boolean} result 是否通过验证
* @param {String} value 字段的值
*/
setValue(param, method, result, value) {
const params = this.form[param]
params.$valid = result
params.$invalid = !result
params.$error[method] = !result
params.$success[method] = result
params.$viewValue = value
}
/**
* 验证所有字段的规则,返回验证是否通过
* @param {Object} data 需要验证数据对象
*/
checkForm(data) {
this.__initData()
for (let param in this.rules) {
this.setView(param)
this.checkParam(param, this.rules[param], data)
}
return this.valid()
}
/**
* 返回验证是否通过
*/
valid() {
return this.size() === 0
}
/**
* 返回错误信息的个数
*/
size() {
return this.errorList.length
}
/**
* 返回所有错误信息
*/
validationErrors() {
return this.errorList
}
}
export default WxValidate

View File

@ -0,0 +1,15 @@
var es6 = require("./es6.wxs");
var getDictLabel = function (value, options) {
var option = es6.find(options, function (el) {
return el.value === value;
});
if (option) {
return option.label;
} else {
return null;
}
};
module.exports = {
getDictLabel: getDictLabel,
};

11
miniprogram/utils/es6.wxs Normal file
View File

@ -0,0 +1,11 @@
function find(arr, callback) {
for (var i = 0; i < arr.length; i++) {
if (callback(arr[i], i, arr)) {
return arr[i];
}
}
return undefined;
}
module.exports = {
find: find,
};

View File

@ -0,0 +1,150 @@
import Message from "tdesign-miniprogram/message/index";
import { setToken } from "./settings";
const authWhitelist = ["/mini-app/login"];
interface RequestOption {
url: string;
method?: "POST" | "PUT" | "DELETE" | "OPTIONS" | "HEAD" | "TRACE" | "CONNECT";
data?: any;
params?: object;
header?: object;
}
interface RequestConfig {
baseUrl: string;
timeout?: number;
}
const buildQueryString = (params: object) => {
const queryParams = [];
for (const key in params) {
if (params.hasOwnProperty(key)) {
// @ts-ignore
const value = encodeURIComponent(params[key]);
queryParams.push(`${encodeURIComponent(key)}=${value}`);
}
}
return `?${queryParams.join("&")}`;
};
class HttpClient {
baseUrl: string;
constructor(config: RequestConfig) {
this.baseUrl = config.baseUrl;
}
request(req: RequestOption) {
let url: string;
let paramsString = "";
if (req.params) {
paramsString = buildQueryString(req.params);
}
if (req.url.startsWith("https://") || req.url.startsWith("http://")) {
url = req.url;
} else {
url = `${this.baseUrl}${req.url}${paramsString}`;
}
const app = getApp();
const header: any = req.header ?? {};
if (!authWhitelist.includes(req.url)) {
header.Authorization = `Bearer ${app.globalData.authToken}`;
}
return new Promise(function (resolve, reject) {
wx.request({
url,
method: req.method,
data: req.data,
header,
success(response) {
let respData: any = response.data;
let statusCode = respData.code;
if (statusCode == 200) {
resolve(respData);
} else {
Message.error({
offset: [20, 32],
duration: 5000,
content: respData.msg,
});
if (statusCode == 401) {
// TODO: remove token & redirect to login
setToken(undefined);
wx.switchTab({
url: "/pages/login/login",
});
}
reject(response.data);
}
},
fail(error) {
Message.error({
offset: [20, 32],
duration: 5000,
content: error.errMsg,
});
reject(error);
},
});
});
}
uploadFile(req: any) {
let url: string;
const app = getApp();
if (req.url.startsWith("https://") || req.url.startsWith("http://")) {
url = req.url;
} else {
url = `${this.baseUrl}${req.url}`;
}
return new Promise((resolve, reject) => {
wx.uploadFile({
url,
filePath: req.file.url,
name: "file",
header: {
Authorization: `Bearer ${app.globalData.authToken}`,
},
success(response) {
let respData: any;
if (typeof response.data === "string") {
try {
respData = JSON.parse(response.data);
} catch {
respData = {};
}
} else {
respData = response.data;
}
let statusCode = respData.code;
if (statusCode == 200) {
resolve(respData);
} else {
Message.error({
offset: [20, 32],
duration: 5000,
content: respData.msg,
});
reject(respData);
}
},
fail: (error) => {
Message.error({
offset: [20, 32],
duration: 5000,
content: error.errMsg,
});
reject(error);
},
});
});
}
}
export const httpClient = new HttpClient({
baseUrl: "https://nine.motse.com.cn/api",
// baseUrl: "http://192.168.0.200:8080",
});
export default httpClient;

View File

@ -0,0 +1,28 @@
export const isInView = () => {
// 获取元素信息
const query = wx.createSelectorQuery();
query.select("#targetElement").boundingClientRect();
query.exec((res) => {
const targetElementInfo = res[0]; // 获取元素位置信息
// 获取屏幕可视区域信息
wx.getSystemInfo({
success: (res) => {
const windowHeight = res.windowHeight; // 屏幕高度
const windowWidth = res.windowWidth; // 屏幕宽度
// 判断元素是否在屏幕可视区域内
if (
targetElementInfo.top >= 0 && // 元素顶部在屏幕内
targetElementInfo.bottom <= windowHeight && // 元素底部在屏幕内
targetElementInfo.left >= 0 && // 元素左侧在屏幕内
targetElementInfo.right <= windowWidth // 元素右侧在屏幕内
) {
console.log("元素在屏幕内");
} else {
console.log("元素不在屏幕内");
}
},
});
});
};

View File

@ -0,0 +1,23 @@
export const setToken = (token?: string) => {
getApp().globalData.authToken = token;
wx.setStorage({
key: "auth-token",
data: token,
});
};
// 如果不存在token则跳转到身份选择页面
export const requiredAuth = () => {
const app = getApp();
if (!app.globalData.authToken) {
wx.redirectTo({
url: "/pages/login/login",
fail: (err) => {
console.log(err);
},
});
}
};
export const getToken = () => {
const token = wx.getStorageSync("auth-token");
return token;
};

View File

@ -0,0 +1,19 @@
var splitTime = function (time) {
return time.split(" ")[0];
};
var formatDate = function (datestr) {
if(!datestr) return null
var date = getDate(datestr);
var year = date.getFullYear();
var month = date.getMonth() + 1;
if (month < 10) month = "0" + month;
var day = date.getDate();
if (day < 0) day = "0" + day;
return year + "-" + month + "-" + day;
};
module.exports = {
splitTime: splitTime,
formatDate: formatDate,
};

19
miniprogram/utils/util.ts Normal file
View File

@ -0,0 +1,19 @@
export const formatTime = (date: Date) => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return (
[year, month, day].map(formatNumber).join('/') +
' ' +
[hour, minute, second].map(formatNumber).join(':')
)
}
const formatNumber = (n: number) => {
const s = n.toString()
return s[1] ? s : '0' + s
}

15
package.json Normal file
View File

@ -0,0 +1,15 @@
{
"name": "miniprogram-ts-less-quickstart",
"version": "1.0.0",
"description": "",
"scripts": {
},
"keywords": [],
"author": "",
"license": "",
"dependencies": {
},
"devDependencies": {
"miniprogram-api-typings": "^2.8.3-1"
}
}

38
project.config.json Normal file
View File

@ -0,0 +1,38 @@
{
"description": "项目配置文件",
"miniprogramRoot": "miniprogram/",
"compileType": "miniprogram",
"setting": {
"useCompilerPlugins": [
"typescript",
"sass"
],
"babelSetting": {
"ignore": [],
"disablePlugins": [],
"outputPath": ""
},
"coverView": false,
"postcss": false,
"minified": false,
"enhance": true,
"showShadowRootInWxmlPanel": false,
"packNpmRelationList": [],
"ignoreUploadUnusedFiles": true,
"es6": true
},
"simulatorType": "wechat",
"simulatorPluginLibVersion": {},
"condition": {},
"srcMiniprogramRoot": "miniprogram/",
"editorSetting": {
"tabIndent": "insertSpaces",
"tabSize": 2
},
"appid": "wx135bf2b5dea9dff1",
"libVersion": "3.0.0",
"packOptions": {
"ignore": [],
"include": []
}
}

View File

@ -0,0 +1,7 @@
{
"description": "项目私有配置文件。此文件中的内容将覆盖 project.config.json 中的相同字段。项目的改动优先同步到此文件中。详见文档https://developers.weixin.qq.com/miniprogram/dev/devtools/projectconfig.html",
"projectname": "pocket-jiuzhang-miniprogram",
"setting": {
"compileHotReLoad": true
}
}

33
tsconfig.json Normal file
View File

@ -0,0 +1,33 @@
{
"compilerOptions": {
"strictNullChecks": true,
"noImplicitAny": true,
"module": "CommonJS",
"target": "ES2020",
"allowJs": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"noImplicitThis": true,
"noImplicitReturns": true,
"alwaysStrict": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"strict": true,
"strictPropertyInitialization": true,
"lib": ["ES2020"],
"paths": {
"tdesign-miniprogram/*": ["./miniprogram/miniprogram_npm/tdesign-miniprogram/*"]
},
"typeRoots": [
"./typings"
]
},
"include": [
"./**/*.ts"
],
"exclude": [
"node_modules"
]
}

10
typings/index.d.ts vendored Normal file
View File

@ -0,0 +1,10 @@
/// <reference path="./types/index.d.ts" />
interface IAppOption {
globalData: {
userInfo?: WechatMiniprogram.UserInfo;
authToken?: string;
permissions?: [];
};
userInfoReadyCallback?: WechatMiniprogram.GetUserInfoSuccessCallback;
}

1
typings/types/index.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference path="./wx/index.d.ts" />

74
typings/types/wx/index.d.ts vendored Normal file
View File

@ -0,0 +1,74 @@
/*! *****************************************************************************
Copyright (c) 2021 Tencent, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
***************************************************************************** */
/// <reference path="./lib.wx.app.d.ts" />
/// <reference path="./lib.wx.page.d.ts" />
/// <reference path="./lib.wx.api.d.ts" />
/// <reference path="./lib.wx.cloud.d.ts" />
/// <reference path="./lib.wx.component.d.ts" />
/// <reference path="./lib.wx.behavior.d.ts" />
/// <reference path="./lib.wx.event.d.ts" />
declare namespace WechatMiniprogram {
type IAnyObject = Record<string, any>
type Optional<F> = F extends (arg: infer P) => infer R ? (arg?: P) => R : F
type OptionalInterface<T> = { [K in keyof T]: Optional<T[K]> }
interface AsyncMethodOptionLike {
success?: (...args: any[]) => void
}
type PromisifySuccessResult<
P,
T extends AsyncMethodOptionLike
> = P extends { success: any }
? void
: P extends { fail: any }
? void
: P extends { complete: any }
? void
: Promise<Parameters<Exclude<T['success'], undefined>>[0]>
}
declare const console: WechatMiniprogram.Console
declare const wx: WechatMiniprogram.Wx
/** 引入模块。返回模块通过 `module.exports` 或 `exports` 暴露的接口。 */
declare function require(
/** 需要引入模块文件相对于当前文件的相对路径,或 npm 模块名,或 npm 模块路径。不支持绝对路径 */
module: string
): any
/** 引入插件。返回插件通过 `main` 暴露的接口。 */
declare function requirePlugin(
/** 需要引入的插件的 alias */
module: string
): any
/** 插件引入当前使用者小程序。返回使用者小程序通过 [插件配置中 `export` 暴露的接口](https://developers.weixin.qq.com/miniprogram/dev/framework/plugin/using.html#%E5%AF%BC%E5%87%BA%E5%88%B0%E6%8F%92%E4%BB%B6)。
*
* 该接口只在插件中存在
*
* 最低基础库: `2.11.1` */
declare function requireMiniProgram(): any
/** 当前模块对象 */
declare let module: {
/** 模块向外暴露的对象,使用 `require` 引用该模块时可以获取 */
exports: any
}
/** `module.exports` 的引用 */
declare let exports: any

19671
typings/types/wx/lib.wx.api.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

270
typings/types/wx/lib.wx.app.d.ts vendored Normal file
View File

@ -0,0 +1,270 @@
/*! *****************************************************************************
Copyright (c) 2021 Tencent, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
***************************************************************************** */
declare namespace WechatMiniprogram.App {
interface ReferrerInfo {
/** 来源小程序或公众号或App的 appId
*
* 以下场景支持返回 referrerInfo.appId
* - 1020公众号 profile 页相关小程序列表): appId
* - 1035公众号自定义菜单来源公众号 appId
* - 1036App 分享消息卡片):来源应用 appId
* - 1037小程序打开小程序来源小程序 appId
* - 1038从另一个小程序返回来源小程序 appId
* - 1043公众号模板消息来源公众号 appId
*/
appId: string
/** 来源小程序传过来的数据scene=1037或1038时支持 */
extraData?: any
}
type SceneValues =
| 1001
| 1005
| 1006
| 1007
| 1008
| 1011
| 1012
| 1013
| 1014
| 1017
| 1019
| 1020
| 1023
| 1024
| 1025
| 1026
| 1027
| 1028
| 1029
| 1030
| 1031
| 1032
| 1034
| 1035
| 1036
| 1037
| 1038
| 1039
| 1042
| 1043
| 1044
| 1045
| 1046
| 1047
| 1048
| 1049
| 1052
| 1053
| 1056
| 1057
| 1058
| 1059
| 1064
| 1067
| 1069
| 1071
| 1072
| 1073
| 1074
| 1077
| 1078
| 1079
| 1081
| 1082
| 1084
| 1089
| 1090
| 1091
| 1092
| 1095
| 1096
| 1097
| 1099
| 1102
| 1124
| 1125
| 1126
| 1129
interface LaunchShowOption {
/** 打开小程序的路径 */
path: string
/** 打开小程序的query */
query: IAnyObject
/** 打开小程序的场景值
* - 1001发现栏小程序主入口「最近使用」列表基础库2.2.4版本起包含「我的小程序」列表)
* - 1005微信首页顶部搜索框的搜索结果页
* - 1006发现栏小程序主入口搜索框的搜索结果页
* - 1007单人聊天会话中的小程序消息卡片
* - 1008群聊会话中的小程序消息卡片
* - 1011扫描二维码
* - 1012长按图片识别二维码
* - 1013扫描手机相册中选取的二维码
* - 1014小程序模板消息
* - 1017前往小程序体验版的入口页
* - 1019微信钱包微信客户端7.0.0版本改为支付入口)
* - 1020公众号 profile 页相关小程序列表
* - 1023安卓系统桌面图标
* - 1024小程序 profile 页
* - 1025扫描一维码
* - 1026发现栏小程序主入口「附近的小程序」列表
* - 1027微信首页顶部搜索框搜索结果页「使用过的小程序」列表
* - 1028我的卡包
* - 1029小程序中的卡券详情页
* - 1030自动化测试下打开小程序
* - 1031长按图片识别一维码
* - 1032扫描手机相册中选取的一维码
* - 1034微信支付完成页
* - 1035公众号自定义菜单
* - 1036App 分享消息卡片
* - 1037小程序打开小程序
* - 1038从另一个小程序返回
* - 1039摇电视
* - 1042添加好友搜索框的搜索结果页
* - 1043公众号模板消息
* - 1044带 shareTicket 的小程序消息卡片 [详情](https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share.html)
* - 1045朋友圈广告
* - 1046朋友圈广告详情页
* - 1047扫描小程序码
* - 1048长按图片识别小程序码
* - 1049扫描手机相册中选取的小程序码
* - 1052卡券的适用门店列表
* - 1053搜一搜的结果页
* - 1056聊天顶部音乐播放器右上角菜单
* - 1057钱包中的银行卡详情页
* - 1058公众号文章
* - 1059体验版小程序绑定邀请页
* - 1064微信首页连Wi-Fi状态栏
* - 1067公众号文章广告
* - 1069移动应用
* - 1071钱包中的银行卡列表页
* - 1072二维码收款页面
* - 1073客服消息列表下发的小程序消息卡片
* - 1074公众号会话下发的小程序消息卡片
* - 1077摇周边
* - 1078微信连Wi-Fi成功提示页
* - 1079微信游戏中心
* - 1081客服消息下发的文字链
* - 1082公众号会话下发的文字链
* - 1084朋友圈广告原生页
* - 1089微信聊天主界面下拉「最近使用」栏基础库2.2.4版本起包含「我的小程序」栏)
* - 1090长按小程序右上角菜单唤出最近使用历史
* - 1091公众号文章商品卡片
* - 1092城市服务入口
* - 1095小程序广告组件
* - 1096聊天记录
* - 1097微信支付签约页
* - 1099页面内嵌插件
* - 1102公众号 profile 页服务预览
* - 1124扫“一物一码”打开小程序
* - 1125长按图片识别“一物一码”
* - 1126扫描手机相册中选取的“一物一码”
* - 1129微信爬虫访问 [详情](https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/sitemap.html)
*/
scene: SceneValues
/** shareTicket详见 [获取更多转发信息]((转发#获取更多转发信息)) */
shareTicket: string
/** 当场景为由从另一个小程序或公众号或App打开时返回此字段 */
referrerInfo?: ReferrerInfo
}
interface PageNotFoundOption {
/** 不存在页面的路径 */
path: string
/** 打开不存在页面的 query */
query: IAnyObject
/** 是否本次启动的首个页面(例如从分享等入口进来,首个页面是开发者配置的分享页面) */
isEntryPage: boolean
}
interface Option {
/** 生命周期回调—监听小程序初始化
*
* 小程序初始化完成时触发,全局只触发一次。
*/
onLaunch(options: LaunchShowOption): void
/** 生命周期回调—监听小程序显示
*
* 小程序启动,或从后台进入前台显示时
*/
onShow(options: LaunchShowOption): void
/** 生命周期回调—监听小程序隐藏
*
* 小程序从前台进入后台时
*/
onHide(): void
/** 错误监听函数
*
* 小程序发生脚本错误,或者 api
*/
onError(/** 错误信息,包含堆栈 */ error: string): void
/** 页面不存在监听函数
*
* 小程序要打开的页面不存在时触发,会带上页面信息回调该函数
*
* **注意:**
* 1. 如果开发者没有添加 `onPageNotFound` 监听,当跳转页面不存在时,将推入微信客户端原生的页面不存在提示页面。
* 2. 如果 `onPageNotFound` 回调中又重定向到另一个不存在的页面,将推入微信客户端原生的页面不存在提示页面,并且不再回调 `onPageNotFound`。
*
* 最低基础库: 1.9.90
*/
onPageNotFound(options: PageNotFoundOption): void
/**
* 小程序有未处理的 Promise 拒绝时触发。也可以使用 [wx.onUnhandledRejection](https://developers.weixin.qq.com/miniprogram/dev/api/base/app/app-event/wx.onUnhandledRejection.html) 绑定监听。注意事项请参考 [wx.onUnhandledRejection](https://developers.weixin.qq.com/miniprogram/dev/api/base/app/app-event/wx.onUnhandledRejection.html)。
* **参数**:与 [wx.onUnhandledRejection](https://developers.weixin.qq.com/miniprogram/dev/api/base/app/app-event/wx.onUnhandledRejection.html) 一致
*/
onUnhandledRejection: OnUnhandledRejectionCallback
/**
* 系统切换主题时触发。也可以使用 wx.onThemeChange 绑定监听。
*
* 最低基础库: 2.11.0
*/
onThemeChange: OnThemeChangeCallback
}
type Instance<T extends IAnyObject> = Option & T
type Options<T extends IAnyObject> = Partial<Option> &
T &
ThisType<Instance<T>>
type TrivialInstance = Instance<IAnyObject>
interface Constructor {
<T extends IAnyObject>(options: Options<T>): void
}
interface GetAppOption {
/** 在 `App` 未定义时返回默认实现。当App被调用时默认实现中定义的属性会被覆盖合并到App中。一般用于独立分包
*
* 最低基础库: 2.2.4
*/
allowDefault?: boolean
}
interface GetApp {
<T = IAnyObject>(opts?: GetAppOption): Instance<T>
}
}
declare let App: WechatMiniprogram.App.Constructor
declare let getApp: WechatMiniprogram.App.GetApp

68
typings/types/wx/lib.wx.behavior.d.ts vendored Normal file
View File

@ -0,0 +1,68 @@
/*! *****************************************************************************
Copyright (c) 2021 Tencent, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
***************************************************************************** */
declare namespace WechatMiniprogram.Behavior {
type BehaviorIdentifier = string
type Instance<
TData extends DataOption,
TProperty extends PropertyOption,
TMethod extends MethodOption,
TCustomInstanceProperty extends IAnyObject = Record<string, never>
> = Component.Instance<TData, TProperty, TMethod, TCustomInstanceProperty>
type TrivialInstance = Instance<IAnyObject, IAnyObject, IAnyObject>
type TrivialOption = Options<IAnyObject, IAnyObject, IAnyObject>
type Options<
TData extends DataOption,
TProperty extends PropertyOption,
TMethod extends MethodOption,
TCustomInstanceProperty extends IAnyObject = Record<string, never>
> = Partial<Data<TData>> &
Partial<Property<TProperty>> &
Partial<Method<TMethod>> &
Partial<OtherOption> &
Partial<Lifetimes> &
ThisType<Instance<TData, TProperty, TMethod, TCustomInstanceProperty>>
interface Constructor {
<
TData extends DataOption,
TProperty extends PropertyOption,
TMethod extends MethodOption,
TCustomInstanceProperty extends IAnyObject = Record<string, never>
>(
options: Options<TData, TProperty, TMethod, TCustomInstanceProperty>
): BehaviorIdentifier
}
type DataOption = Component.DataOption
type PropertyOption = Component.PropertyOption
type MethodOption = Component.MethodOption
type Data<D extends DataOption> = Component.Data<D>
type Property<P extends PropertyOption> = Component.Property<P>
type Method<M extends MethodOption> = Component.Method<M>
type DefinitionFilter = Component.DefinitionFilter
type Lifetimes = Component.Lifetimes
type OtherOption = Omit<Component.OtherOption, 'options'>
}
/** 注册一个 `behavior`,接受一个 `Object` 类型的参数。*/
declare let Behavior: WechatMiniprogram.Behavior.Constructor

924
typings/types/wx/lib.wx.cloud.d.ts vendored Normal file
View File

@ -0,0 +1,924 @@
/*! *****************************************************************************
Copyright (c) 2021 Tencent, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
***************************************************************************** */
interface IAPIError {
errMsg: string
}
interface IAPIParam<T = any> {
config?: ICloudConfig
success?: (res: T) => void
fail?: (err: IAPIError) => void
complete?: (val: T | IAPIError) => void
}
interface IAPISuccessParam {
errMsg: string
}
type IAPICompleteParam = IAPISuccessParam | IAPIError
type IAPIFunction<T, P extends IAPIParam<T>> = (param?: P) => Promise<T>
interface IInitCloudConfig {
env?:
| string
| {
database?: string
functions?: string
storage?: string
}
traceUser?: boolean
}
interface ICloudConfig {
env?: string
traceUser?: boolean
}
interface IICloudAPI {
init: (config?: IInitCloudConfig) => void
[api: string]: AnyFunction | IAPIFunction<any, any>
}
interface ICloudService {
name: string
getAPIs: () => { [name: string]: IAPIFunction<any, any> }
}
interface ICloudServices {
[serviceName: string]: ICloudService
}
interface ICloudMetaData {
session_id: string
}
declare class InternalSymbol {}
interface AnyObject {
[x: string]: any
}
type AnyArray = any[]
type AnyFunction = (...args: any[]) => any
/**
* extend wx with cloud
*/
interface WxCloud {
init: (config?: ICloudConfig) => void
callFunction(param: OQ<ICloud.CallFunctionParam>): void
callFunction(
param: RQ<ICloud.CallFunctionParam>
): Promise<ICloud.CallFunctionResult>
uploadFile(param: OQ<ICloud.UploadFileParam>): WechatMiniprogram.UploadTask
uploadFile(
param: RQ<ICloud.UploadFileParam>
): Promise<ICloud.UploadFileResult>
downloadFile(
param: OQ<ICloud.DownloadFileParam>
): WechatMiniprogram.DownloadTask
downloadFile(
param: RQ<ICloud.DownloadFileParam>
): Promise<ICloud.DownloadFileResult>
getTempFileURL(param: OQ<ICloud.GetTempFileURLParam>): void
getTempFileURL(
param: RQ<ICloud.GetTempFileURLParam>
): Promise<ICloud.GetTempFileURLResult>
deleteFile(param: OQ<ICloud.DeleteFileParam>): void
deleteFile(
param: RQ<ICloud.DeleteFileParam>
): Promise<ICloud.DeleteFileResult>
database: (config?: ICloudConfig) => DB.Database
CloudID: ICloud.ICloudIDConstructor
CDN: ICloud.ICDNConstructor
}
declare namespace ICloud {
interface ICloudAPIParam<T = any> extends IAPIParam<T> {
config?: ICloudConfig
}
// === API: callFunction ===
type CallFunctionData = AnyObject
interface CallFunctionResult extends IAPISuccessParam {
result: AnyObject | string | undefined
}
interface CallFunctionParam extends ICloudAPIParam<CallFunctionResult> {
name: string
data?: CallFunctionData
slow?: boolean
}
// === end ===
// === API: uploadFile ===
interface UploadFileResult extends IAPISuccessParam {
fileID: string
statusCode: number
}
interface UploadFileParam extends ICloudAPIParam<UploadFileResult> {
cloudPath: string
filePath: string
header?: AnyObject
}
// === end ===
// === API: downloadFile ===
interface DownloadFileResult extends IAPISuccessParam {
tempFilePath: string
statusCode: number
}
interface DownloadFileParam extends ICloudAPIParam<DownloadFileResult> {
fileID: string
cloudPath?: string
}
// === end ===
// === API: getTempFileURL ===
interface GetTempFileURLResult extends IAPISuccessParam {
fileList: GetTempFileURLResultItem[]
}
interface GetTempFileURLResultItem {
fileID: string
tempFileURL: string
maxAge: number
status: number
errMsg: string
}
interface GetTempFileURLParam extends ICloudAPIParam<GetTempFileURLResult> {
fileList: string[]
}
// === end ===
// === API: deleteFile ===
interface DeleteFileResult extends IAPISuccessParam {
fileList: DeleteFileResultItem[]
}
interface DeleteFileResultItem {
fileID: string
status: number
errMsg: string
}
interface DeleteFileParam extends ICloudAPIParam<DeleteFileResult> {
fileList: string[]
}
// === end ===
// === API: CloudID ===
abstract class CloudID {
constructor(cloudID: string)
}
interface ICloudIDConstructor {
new (cloudId: string): CloudID
(cloudId: string): CloudID
}
// === end ===
// === API: CDN ===
abstract class CDN {
target: string | ArrayBuffer | ICDNFilePathSpec
constructor(target: string | ArrayBuffer | ICDNFilePathSpec)
}
interface ICDNFilePathSpec {
type: 'filePath'
filePath: string
}
interface ICDNConstructor {
new (options: string | ArrayBuffer | ICDNFilePathSpec): CDN
(options: string | ArrayBuffer | ICDNFilePathSpec): CDN
}
// === end ===
}
// === Database ===
declare namespace DB {
/**
* The class of all exposed cloud database instances
*/
class Database {
readonly config: ICloudConfig
readonly command: DatabaseCommand
readonly Geo: IGeo
readonly serverDate: () => ServerDate
readonly RegExp: IRegExpConstructor
private constructor()
collection(collectionName: string): CollectionReference
}
class CollectionReference extends Query {
readonly collectionName: string
private constructor(name: string, database: Database)
doc(docId: string | number): DocumentReference
add(options: OQ<IAddDocumentOptions>): void
add(options: RQ<IAddDocumentOptions>): Promise<IAddResult>
}
class DocumentReference {
private constructor(docId: string | number, database: Database)
field(object: Record<string, any>): this
get(options: OQ<IGetDocumentOptions>): void
get(options?: RQ<IGetDocumentOptions>): Promise<IQuerySingleResult>
set(options: OQ<ISetSingleDocumentOptions>): void
set(options?: RQ<ISetSingleDocumentOptions>): Promise<ISetResult>
update(options: OQ<IUpdateSingleDocumentOptions>): void
update(
options?: RQ<IUpdateSingleDocumentOptions>
): Promise<IUpdateResult>
remove(options: OQ<IRemoveSingleDocumentOptions>): void
remove(
options?: RQ<IRemoveSingleDocumentOptions>
): Promise<IRemoveResult>
watch(options: IWatchOptions): RealtimeListener
}
class RealtimeListener {
// "And Now His Watch Is Ended"
close: () => Promise<void>
}
class Query {
where(condition: IQueryCondition): Query
orderBy(fieldPath: string, order: string): Query
limit(max: number): Query
skip(offset: number): Query
field(object: Record<string, any>): Query
get(options: OQ<IGetDocumentOptions>): void
get(options?: RQ<IGetDocumentOptions>): Promise<IQueryResult>
count(options: OQ<ICountDocumentOptions>): void
count(options?: RQ<ICountDocumentOptions>): Promise<ICountResult>
watch(options: IWatchOptions): RealtimeListener
}
interface DatabaseCommand {
eq(val: any): DatabaseQueryCommand
neq(val: any): DatabaseQueryCommand
gt(val: any): DatabaseQueryCommand
gte(val: any): DatabaseQueryCommand
lt(val: any): DatabaseQueryCommand
lte(val: any): DatabaseQueryCommand
in(val: any[]): DatabaseQueryCommand
nin(val: any[]): DatabaseQueryCommand
geoNear(options: IGeoNearCommandOptions): DatabaseQueryCommand
geoWithin(options: IGeoWithinCommandOptions): DatabaseQueryCommand
geoIntersects(
options: IGeoIntersectsCommandOptions
): DatabaseQueryCommand
and(
...expressions: Array<DatabaseLogicCommand | IQueryCondition>
): DatabaseLogicCommand
or(
...expressions: Array<DatabaseLogicCommand | IQueryCondition>
): DatabaseLogicCommand
nor(
...expressions: Array<DatabaseLogicCommand | IQueryCondition>
): DatabaseLogicCommand
not(expression: DatabaseLogicCommand): DatabaseLogicCommand
exists(val: boolean): DatabaseQueryCommand
mod(divisor: number, remainder: number): DatabaseQueryCommand
all(val: any[]): DatabaseQueryCommand
elemMatch(val: any): DatabaseQueryCommand
size(val: number): DatabaseQueryCommand
set(val: any): DatabaseUpdateCommand
remove(): DatabaseUpdateCommand
inc(val: number): DatabaseUpdateCommand
mul(val: number): DatabaseUpdateCommand
min(val: number): DatabaseUpdateCommand
max(val: number): DatabaseUpdateCommand
rename(val: string): DatabaseUpdateCommand
bit(val: number): DatabaseUpdateCommand
push(...values: any[]): DatabaseUpdateCommand
pop(): DatabaseUpdateCommand
shift(): DatabaseUpdateCommand
unshift(...values: any[]): DatabaseUpdateCommand
addToSet(val: any): DatabaseUpdateCommand
pull(val: any): DatabaseUpdateCommand
pullAll(val: any): DatabaseUpdateCommand
project: {
slice(val: number | [number, number]): DatabaseProjectionCommand
}
aggregate: {
__safe_props__?: Set<string>
abs(val: any): DatabaseAggregateCommand
add(val: any): DatabaseAggregateCommand
addToSet(val: any): DatabaseAggregateCommand
allElementsTrue(val: any): DatabaseAggregateCommand
and(val: any): DatabaseAggregateCommand
anyElementTrue(val: any): DatabaseAggregateCommand
arrayElemAt(val: any): DatabaseAggregateCommand
arrayToObject(val: any): DatabaseAggregateCommand
avg(val: any): DatabaseAggregateCommand
ceil(val: any): DatabaseAggregateCommand
cmp(val: any): DatabaseAggregateCommand
concat(val: any): DatabaseAggregateCommand
concatArrays(val: any): DatabaseAggregateCommand
cond(val: any): DatabaseAggregateCommand
convert(val: any): DatabaseAggregateCommand
dateFromParts(val: any): DatabaseAggregateCommand
dateToParts(val: any): DatabaseAggregateCommand
dateFromString(val: any): DatabaseAggregateCommand
dateToString(val: any): DatabaseAggregateCommand
dayOfMonth(val: any): DatabaseAggregateCommand
dayOfWeek(val: any): DatabaseAggregateCommand
dayOfYear(val: any): DatabaseAggregateCommand
divide(val: any): DatabaseAggregateCommand
eq(val: any): DatabaseAggregateCommand
exp(val: any): DatabaseAggregateCommand
filter(val: any): DatabaseAggregateCommand
first(val: any): DatabaseAggregateCommand
floor(val: any): DatabaseAggregateCommand
gt(val: any): DatabaseAggregateCommand
gte(val: any): DatabaseAggregateCommand
hour(val: any): DatabaseAggregateCommand
ifNull(val: any): DatabaseAggregateCommand
in(val: any): DatabaseAggregateCommand
indexOfArray(val: any): DatabaseAggregateCommand
indexOfBytes(val: any): DatabaseAggregateCommand
indexOfCP(val: any): DatabaseAggregateCommand
isArray(val: any): DatabaseAggregateCommand
isoDayOfWeek(val: any): DatabaseAggregateCommand
isoWeek(val: any): DatabaseAggregateCommand
isoWeekYear(val: any): DatabaseAggregateCommand
last(val: any): DatabaseAggregateCommand
let(val: any): DatabaseAggregateCommand
literal(val: any): DatabaseAggregateCommand
ln(val: any): DatabaseAggregateCommand
log(val: any): DatabaseAggregateCommand
log10(val: any): DatabaseAggregateCommand
lt(val: any): DatabaseAggregateCommand
lte(val: any): DatabaseAggregateCommand
ltrim(val: any): DatabaseAggregateCommand
map(val: any): DatabaseAggregateCommand
max(val: any): DatabaseAggregateCommand
mergeObjects(val: any): DatabaseAggregateCommand
meta(val: any): DatabaseAggregateCommand
min(val: any): DatabaseAggregateCommand
millisecond(val: any): DatabaseAggregateCommand
minute(val: any): DatabaseAggregateCommand
mod(val: any): DatabaseAggregateCommand
month(val: any): DatabaseAggregateCommand
multiply(val: any): DatabaseAggregateCommand
neq(val: any): DatabaseAggregateCommand
not(val: any): DatabaseAggregateCommand
objectToArray(val: any): DatabaseAggregateCommand
or(val: any): DatabaseAggregateCommand
pow(val: any): DatabaseAggregateCommand
push(val: any): DatabaseAggregateCommand
range(val: any): DatabaseAggregateCommand
reduce(val: any): DatabaseAggregateCommand
reverseArray(val: any): DatabaseAggregateCommand
rtrim(val: any): DatabaseAggregateCommand
second(val: any): DatabaseAggregateCommand
setDifference(val: any): DatabaseAggregateCommand
setEquals(val: any): DatabaseAggregateCommand
setIntersection(val: any): DatabaseAggregateCommand
setIsSubset(val: any): DatabaseAggregateCommand
setUnion(val: any): DatabaseAggregateCommand
size(val: any): DatabaseAggregateCommand
slice(val: any): DatabaseAggregateCommand
split(val: any): DatabaseAggregateCommand
sqrt(val: any): DatabaseAggregateCommand
stdDevPop(val: any): DatabaseAggregateCommand
stdDevSamp(val: any): DatabaseAggregateCommand
strcasecmp(val: any): DatabaseAggregateCommand
strLenBytes(val: any): DatabaseAggregateCommand
strLenCP(val: any): DatabaseAggregateCommand
substr(val: any): DatabaseAggregateCommand
substrBytes(val: any): DatabaseAggregateCommand
substrCP(val: any): DatabaseAggregateCommand
subtract(val: any): DatabaseAggregateCommand
sum(val: any): DatabaseAggregateCommand
switch(val: any): DatabaseAggregateCommand
toBool(val: any): DatabaseAggregateCommand
toDate(val: any): DatabaseAggregateCommand
toDecimal(val: any): DatabaseAggregateCommand
toDouble(val: any): DatabaseAggregateCommand
toInt(val: any): DatabaseAggregateCommand
toLong(val: any): DatabaseAggregateCommand
toObjectId(val: any): DatabaseAggregateCommand
toString(val: any): DatabaseAggregateCommand
toLower(val: any): DatabaseAggregateCommand
toUpper(val: any): DatabaseAggregateCommand
trim(val: any): DatabaseAggregateCommand
trunc(val: any): DatabaseAggregateCommand
type(val: any): DatabaseAggregateCommand
week(val: any): DatabaseAggregateCommand
year(val: any): DatabaseAggregateCommand
zip(val: any): DatabaseAggregateCommand
}
}
class DatabaseAggregateCommand {}
enum LOGIC_COMMANDS_LITERAL {
AND = 'and',
OR = 'or',
NOT = 'not',
NOR = 'nor'
}
class DatabaseLogicCommand {
and(...expressions: DatabaseLogicCommand[]): DatabaseLogicCommand
or(...expressions: DatabaseLogicCommand[]): DatabaseLogicCommand
nor(...expressions: DatabaseLogicCommand[]): DatabaseLogicCommand
not(expression: DatabaseLogicCommand): DatabaseLogicCommand
}
enum QUERY_COMMANDS_LITERAL {
// comparison
EQ = 'eq',
NEQ = 'neq',
GT = 'gt',
GTE = 'gte',
LT = 'lt',
LTE = 'lte',
IN = 'in',
NIN = 'nin',
// geo
GEO_NEAR = 'geoNear',
GEO_WITHIN = 'geoWithin',
GEO_INTERSECTS = 'geoIntersects',
// element
EXISTS = 'exists',
// evaluation
MOD = 'mod',
// array
ALL = 'all',
ELEM_MATCH = 'elemMatch',
SIZE = 'size'
}
class DatabaseQueryCommand extends DatabaseLogicCommand {
eq(val: any): DatabaseLogicCommand
neq(val: any): DatabaseLogicCommand
gt(val: any): DatabaseLogicCommand
gte(val: any): DatabaseLogicCommand
lt(val: any): DatabaseLogicCommand
lte(val: any): DatabaseLogicCommand
in(val: any[]): DatabaseLogicCommand
nin(val: any[]): DatabaseLogicCommand
exists(val: boolean): DatabaseLogicCommand
mod(divisor: number, remainder: number): DatabaseLogicCommand
all(val: any[]): DatabaseLogicCommand
elemMatch(val: any): DatabaseLogicCommand
size(val: number): DatabaseLogicCommand
geoNear(options: IGeoNearCommandOptions): DatabaseLogicCommand
geoWithin(options: IGeoWithinCommandOptions): DatabaseLogicCommand
geoIntersects(
options: IGeoIntersectsCommandOptions
): DatabaseLogicCommand
}
enum PROJECTION_COMMANDS_LITERAL {
SLICE = 'slice'
}
class DatabaseProjectionCommand {}
enum UPDATE_COMMANDS_LITERAL {
// field
SET = 'set',
REMOVE = 'remove',
INC = 'inc',
MUL = 'mul',
MIN = 'min',
MAX = 'max',
RENAME = 'rename',
// bitwise
BIT = 'bit',
// array
PUSH = 'push',
POP = 'pop',
SHIFT = 'shift',
UNSHIFT = 'unshift',
ADD_TO_SET = 'addToSet',
PULL = 'pull',
PULL_ALL = 'pullAll'
}
class DatabaseUpdateCommand {}
class Batch {}
/**
* A contract that all API provider must adhere to
*/
class APIBaseContract<
PromiseReturn,
CallbackReturn,
Param extends IAPIParam,
Context = any
> {
getContext(param: Param): Context
/**
* In case of callback-style invocation, this function will be called
*/
getCallbackReturn(param: Param, context: Context): CallbackReturn
getFinalParam<T extends Param>(param: Param, context: Context): T
run<T extends Param>(param: T): Promise<PromiseReturn>
}
interface IGeoPointConstructor {
new (longitude: number, latitide: number): GeoPoint
new (geojson: IGeoJSONPoint): GeoPoint
(longitude: number, latitide: number): GeoPoint
(geojson: IGeoJSONPoint): GeoPoint
}
interface IGeoMultiPointConstructor {
new (points: GeoPoint[] | IGeoJSONMultiPoint): GeoMultiPoint
(points: GeoPoint[] | IGeoJSONMultiPoint): GeoMultiPoint
}
interface IGeoLineStringConstructor {
new (points: GeoPoint[] | IGeoJSONLineString): GeoLineString
(points: GeoPoint[] | IGeoJSONLineString): GeoLineString
}
interface IGeoMultiLineStringConstructor {
new (
lineStrings: GeoLineString[] | IGeoJSONMultiLineString
): GeoMultiLineString
(
lineStrings: GeoLineString[] | IGeoJSONMultiLineString
): GeoMultiLineString
}
interface IGeoPolygonConstructor {
new (lineStrings: GeoLineString[] | IGeoJSONPolygon): GeoPolygon
(lineStrings: GeoLineString[] | IGeoJSONPolygon): GeoPolygon
}
interface IGeoMultiPolygonConstructor {
new (polygons: GeoPolygon[] | IGeoJSONMultiPolygon): GeoMultiPolygon
(polygons: GeoPolygon[] | IGeoJSONMultiPolygon): GeoMultiPolygon
}
interface IGeo {
Point: IGeoPointConstructor
MultiPoint: IGeoMultiPointConstructor
LineString: IGeoLineStringConstructor
MultiLineString: IGeoMultiLineStringConstructor
Polygon: IGeoPolygonConstructor
MultiPolygon: IGeoMultiPolygonConstructor
}
interface IGeoJSONPoint {
type: 'Point'
coordinates: [number, number]
}
interface IGeoJSONMultiPoint {
type: 'MultiPoint'
coordinates: Array<[number, number]>
}
interface IGeoJSONLineString {
type: 'LineString'
coordinates: Array<[number, number]>
}
interface IGeoJSONMultiLineString {
type: 'MultiLineString'
coordinates: Array<Array<[number, number]>>
}
interface IGeoJSONPolygon {
type: 'Polygon'
coordinates: Array<Array<[number, number]>>
}
interface IGeoJSONMultiPolygon {
type: 'MultiPolygon'
coordinates: Array<Array<Array<[number, number]>>>
}
type IGeoJSONObject =
| IGeoJSONPoint
| IGeoJSONMultiPoint
| IGeoJSONLineString
| IGeoJSONMultiLineString
| IGeoJSONPolygon
| IGeoJSONMultiPolygon
abstract class GeoPoint {
longitude: number
latitude: number
constructor(longitude: number, latitude: number)
toJSON(): Record<string, any>
toString(): string
}
abstract class GeoMultiPoint {
points: GeoPoint[]
constructor(points: GeoPoint[])
toJSON(): IGeoJSONMultiPoint
toString(): string
}
abstract class GeoLineString {
points: GeoPoint[]
constructor(points: GeoPoint[])
toJSON(): IGeoJSONLineString
toString(): string
}
abstract class GeoMultiLineString {
lines: GeoLineString[]
constructor(lines: GeoLineString[])
toJSON(): IGeoJSONMultiLineString
toString(): string
}
abstract class GeoPolygon {
lines: GeoLineString[]
constructor(lines: GeoLineString[])
toJSON(): IGeoJSONPolygon
toString(): string
}
abstract class GeoMultiPolygon {
polygons: GeoPolygon[]
constructor(polygons: GeoPolygon[])
toJSON(): IGeoJSONMultiPolygon
toString(): string
}
type GeoInstance =
| GeoPoint
| GeoMultiPoint
| GeoLineString
| GeoMultiLineString
| GeoPolygon
| GeoMultiPolygon
interface IGeoNearCommandOptions {
geometry: GeoPoint
maxDistance?: number
minDistance?: number
}
interface IGeoWithinCommandOptions {
geometry: GeoPolygon | GeoMultiPolygon
}
interface IGeoIntersectsCommandOptions {
geometry:
| GeoPoint
| GeoMultiPoint
| GeoLineString
| GeoMultiLineString
| GeoPolygon
| GeoMultiPolygon
}
interface IServerDateOptions {
offset: number
}
abstract class ServerDate {
readonly options: IServerDateOptions
constructor(options?: IServerDateOptions)
}
interface IRegExpOptions {
regexp: string
options?: string
}
interface IRegExpConstructor {
new (options: IRegExpOptions): RegExp
(options: IRegExpOptions): RegExp
}
abstract class RegExp {
readonly regexp: string
readonly options: string
constructor(options: IRegExpOptions)
}
type DocumentId = string | number
interface IDocumentData {
_id?: DocumentId
[key: string]: any
}
type IDBAPIParam = IAPIParam
interface IAddDocumentOptions extends IDBAPIParam {
data: IDocumentData
}
type IGetDocumentOptions = IDBAPIParam
type ICountDocumentOptions = IDBAPIParam
interface IUpdateDocumentOptions extends IDBAPIParam {
data: IUpdateCondition
}
interface IUpdateSingleDocumentOptions extends IDBAPIParam {
data: IUpdateCondition
}
interface ISetDocumentOptions extends IDBAPIParam {
data: IUpdateCondition
}
interface ISetSingleDocumentOptions extends IDBAPIParam {
data: IUpdateCondition
}
interface IRemoveDocumentOptions extends IDBAPIParam {
query: IQueryCondition
}
type IRemoveSingleDocumentOptions = IDBAPIParam
interface IWatchOptions {
// server realtime data init & change event
onChange: (snapshot: ISnapshot) => void
// error while connecting / listening
onError: (error: any) => void
}
interface ISnapshot {
id: number
docChanges: ISingleDBEvent[]
docs: Record<string, any>
type?: SnapshotType
}
type SnapshotType = 'init'
interface ISingleDBEvent {
id: number
dataType: DataType
queueType: QueueType
docId: string
doc: Record<string, any>
updatedFields?: Record<string, any>
removedFields?: string[]
}
type DataType = 'init' | 'update' | 'replace' | 'add' | 'remove' | 'limit'
type QueueType = 'init' | 'enqueue' | 'dequeue' | 'update'
interface IQueryCondition {
[key: string]: any
}
type IStringQueryCondition = string
interface IQueryResult extends IAPISuccessParam {
data: IDocumentData[]
}
interface IQuerySingleResult extends IAPISuccessParam {
data: IDocumentData
}
interface IUpdateCondition {
[key: string]: any
}
type IStringUpdateCondition = string
interface IAddResult extends IAPISuccessParam {
_id: DocumentId
}
interface IUpdateResult extends IAPISuccessParam {
stats: {
updated: number
// created: number,
}
}
interface ISetResult extends IAPISuccessParam {
_id: DocumentId
stats: {
updated: number
created: number
}
}
interface IRemoveResult extends IAPISuccessParam {
stats: {
removed: number
}
}
interface ICountResult extends IAPISuccessParam {
total: number
}
}
type Optional<T> = { [K in keyof T]+?: T[K] }
type OQ<
T extends Optional<
Record<'complete' | 'success' | 'fail', (...args: any[]) => any>
>
> =
| (RQ<T> & Required<Pick<T, 'success'>>)
| (RQ<T> & Required<Pick<T, 'fail'>>)
| (RQ<T> & Required<Pick<T, 'complete'>>)
| (RQ<T> & Required<Pick<T, 'success' | 'fail'>>)
| (RQ<T> & Required<Pick<T, 'success' | 'complete'>>)
| (RQ<T> & Required<Pick<T, 'fail' | 'complete'>>)
| (RQ<T> & Required<Pick<T, 'fail' | 'complete' | 'success'>>)
type RQ<
T extends Optional<
Record<'complete' | 'success' | 'fail', (...args: any[]) => any>
>
> = Pick<T, Exclude<keyof T, 'complete' | 'success' | 'fail'>>

636
typings/types/wx/lib.wx.component.d.ts vendored Normal file
View File

@ -0,0 +1,636 @@
/*! *****************************************************************************
Copyright (c) 2021 Tencent, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
***************************************************************************** */
declare namespace WechatMiniprogram.Component {
type Instance<
TData extends DataOption,
TProperty extends PropertyOption,
TMethod extends Partial<MethodOption>,
TCustomInstanceProperty extends IAnyObject = {},
TIsPage extends boolean = false
> = InstanceProperties &
InstanceMethods<TData> &
TMethod &
(TIsPage extends true ? Page.ILifetime : {}) &
TCustomInstanceProperty & {
/** 组件数据,**包括内部数据和属性值** */
data: TData & PropertyOptionToData<TProperty>
/** 组件数据,**包括内部数据和属性值**(与 `data` 一致) */
properties: TData & PropertyOptionToData<TProperty>
}
type TrivialInstance = Instance<
IAnyObject,
IAnyObject,
IAnyObject,
IAnyObject
>
type TrivialOption = Options<IAnyObject, IAnyObject, IAnyObject, IAnyObject>
type Options<
TData extends DataOption,
TProperty extends PropertyOption,
TMethod extends MethodOption,
TCustomInstanceProperty extends IAnyObject = {},
TIsPage extends boolean = false
> = Partial<Data<TData>> &
Partial<Property<TProperty>> &
Partial<Method<TMethod, TIsPage>> &
Partial<OtherOption> &
Partial<Lifetimes> &
ThisType<
Instance<
TData,
TProperty,
TMethod,
TCustomInstanceProperty,
TIsPage
>
>
interface Constructor {
<
TData extends DataOption,
TProperty extends PropertyOption,
TMethod extends MethodOption,
TCustomInstanceProperty extends IAnyObject = {},
TIsPage extends boolean = false
>(
options: Options<
TData,
TProperty,
TMethod,
TCustomInstanceProperty,
TIsPage
>
): string
}
type DataOption = Record<string, any>
type PropertyOption = Record<string, AllProperty>
type MethodOption = Record<string, Function>
interface Data<D extends DataOption> {
/** 组件的内部数据,和 `properties` 一同用于组件的模板渲染 */
data?: D
}
interface Property<P extends PropertyOption> {
/** 组件的对外属性,是属性名到属性设置的映射表 */
properties: P
}
interface Method<M extends MethodOption, TIsPage extends boolean = false> {
/** 组件的方法,包括事件响应函数和任意的自定义方法,关于事件响应函数的使用,参见 [组件间通信与事件](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/events.html) */
methods: M & (TIsPage extends true ? Partial<Page.ILifetime> : {})
}
type PropertyType =
| StringConstructor
| NumberConstructor
| BooleanConstructor
| ArrayConstructor
| ObjectConstructor
| null
type ValueType<T extends PropertyType> = T extends null
? any
: T extends StringConstructor
? string
: T extends NumberConstructor
? number
: T extends BooleanConstructor
? boolean
: T extends ArrayConstructor
? any[]
: T extends ObjectConstructor
? IAnyObject
: never
type FullProperty<T extends PropertyType> = {
/** 属性类型 */
type: T
/** 属性初始值 */
value?: ValueType<T>
/** 属性值被更改时的响应函数 */
observer?:
| string
| ((
newVal: ValueType<T>,
oldVal: ValueType<T>,
changedPath: Array<string | number>
) => void)
/** 属性的类型(可以指定多个) */
optionalTypes?: ShortProperty[]
}
type AllFullProperty =
| FullProperty<StringConstructor>
| FullProperty<NumberConstructor>
| FullProperty<BooleanConstructor>
| FullProperty<ArrayConstructor>
| FullProperty<ObjectConstructor>
| FullProperty<null>
type ShortProperty =
| StringConstructor
| NumberConstructor
| BooleanConstructor
| ArrayConstructor
| ObjectConstructor
| null
type AllProperty = AllFullProperty | ShortProperty
type PropertyToData<T extends AllProperty> = T extends ShortProperty
? ValueType<T>
: FullPropertyToData<Exclude<T, ShortProperty>>
type FullPropertyToData<T extends AllFullProperty> = ValueType<T['type']>
type PropertyOptionToData<P extends PropertyOption> = {
[name in keyof P]: PropertyToData<P[name]>
}
interface InstanceProperties {
/** 组件的文件路径 */
is: string
/** 节点id */
id: string
/** 节点dataset */
dataset: Record<string, string>
}
interface InstanceMethods<D extends DataOption> {
/** `setData` 函数用于将数据从逻辑层发送到视图层
*(异步),同时改变对应的 `this.data` 的值(同步)。
*
* **注意:**
*
* 1. **直接修改 this.data 而不调用 this.setData 是无法改变页面的状态的,还会造成数据不一致**。
* 1. 仅支持设置可 JSON 化的数据。
* 1. 单次设置的数据不能超过1024kB请尽量避免一次设置过多的数据。
* 1. 请不要把 data 中任何一项的 value 设为 `undefined` ,否则这一项将不被设置并可能遗留一些潜在问题。
*/
setData(
/** 这次要改变的数据
*
* 以 `key: value` 的形式表示,将 `this.data` 中的 `key` 对应的值改变成 `value`。
*
* 其中 `key` 可以以数据路径的形式给出,支持改变数组中的某一项或对象的某个属性,如 `array[2].message``a.b.c.d`,并且不需要在 this.data 中预先定义。
*/
data: Partial<D> & IAnyObject,
/** setData引起的界面更新渲染完毕后的回调函数最低基础库 `1.5.0` */
callback?: () => void
): void
/** 检查组件是否具有 `behavior` 检查时会递归检查被直接或间接引入的所有behavior */
hasBehavior(behavior: Behavior.BehaviorIdentifier): void
/** 触发事件,参见组件事件 */
triggerEvent<DetailType = any>(
name: string,
detail?: DetailType,
options?: TriggerEventOption
): void
/** 创建一个 SelectorQuery 对象,选择器选取范围为这个组件实例内 */
createSelectorQuery(): SelectorQuery
/** 创建一个 IntersectionObserver 对象,选择器选取范围为这个组件实例内 */
createIntersectionObserver(
options: CreateIntersectionObserverOption
): IntersectionObserver
/** 使用选择器选择组件实例节点,返回匹配到的第一个组件实例对象(会被 `wx://component-export` 影响) */
selectComponent(selector: string): TrivialInstance
/** 使用选择器选择组件实例节点,返回匹配到的全部组件实例对象组成的数组 */
selectAllComponents(selector: string): TrivialInstance[]
/**
* 选取当前组件节点所在的组件实例(即组件的引用者),返回它的组件实例对象(会被 `wx://component-export` 影响)
*
* 最低基础库版本:[`2.8.2`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
**/
selectOwnerComponent(): TrivialInstance
/** 获取这个关系所对应的所有关联节点,参见 组件间关系 */
getRelationNodes(relationKey: string): TrivialInstance[]
/**
* 立刻执行 callback ,其中的多个 setData 之间不会触发界面绘制(只有某些特殊场景中需要,如用于在不同组件同时 setData 时进行界面绘制同步)
*
* 最低基础库版本:[`2.4.0`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
**/
groupSetData(callback?: () => void): void
/**
* 返回当前页面的 custom-tab-bar 的组件实例
*
* 最低基础库版本:[`2.6.2`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
**/
getTabBar(): TrivialInstance
/**
* 返回页面标识符(一个字符串),可以用来判断几个自定义组件实例是不是在同一个页面内
*
* 最低基础库版本:[`2.7.1`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
**/
getPageId(): string
/**
* 执行关键帧动画,详见[动画](https://developers.weixin.qq.com/miniprogram/dev/framework/view/animation.html)
*
* 最低基础库版本:[`2.9.0`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
**/
animate(
selector: string,
keyFrames: KeyFrame[],
duration: number,
callback?: () => void
): void
/**
* 执行关键帧动画,详见[动画](https://developers.weixin.qq.com/miniprogram/dev/framework/view/animation.html)
*
* 最低基础库版本:[`2.9.0`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
**/
animate(
selector: string,
keyFrames: ScrollTimelineKeyframe[],
duration: number,
scrollTimeline: ScrollTimelineOption
): void
/**
* 清除关键帧动画,详见[动画](https://developers.weixin.qq.com/miniprogram/dev/framework/view/animation.html)
*
* 最低基础库版本:[`2.9.0`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
**/
clearAnimation(selector: string, callback: () => void): void
/**
* 清除关键帧动画,详见[动画](https://developers.weixin.qq.com/miniprogram/dev/framework/view/animation.html)
*
* 最低基础库版本:[`2.9.0`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
**/
clearAnimation(
selector: string,
options?: ClearAnimationOptions,
callback?: () => void
): void
getOpenerEventChannel(): EventChannel
}
interface ComponentOptions {
/**
* [启用多slot支持](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html#组件wxml的slot)
*/
multipleSlots?: boolean
/**
* [组件样式隔离](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html#组件样式隔离)
*/
addGlobalClass?: boolean
/**
* [组件样式隔离](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html#组件样式隔离)
*/
styleIsolation?:
| 'isolated'
| 'apply-shared'
| 'shared'
| 'page-isolated'
| 'page-apply-shared'
| 'page-shared'
/**
* [纯数据字段](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/pure-data.html) 是一些不用于界面渲染的 data 字段,可以用于提升页面更新性能。从小程序基础库版本 2.8.2 开始支持。
*/
pureDataPattern?: RegExp
/**
* [虚拟化组件节点](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html#%E8%99%9A%E6%8B%9F%E5%8C%96%E7%BB%84%E4%BB%B6%E8%8A%82%E7%82%B9) 使自定义组件内部的第一层节点由自定义组件本身完全决定。从小程序基础库版本 [`2.11.2`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html) 开始支持 */
virtualHost?: boolean
}
interface TriggerEventOption {
/** 事件是否冒泡
*
* 默认值: `false`
*/
bubbles?: boolean
/** 事件是否可以穿越组件边界为false时事件将只能在引用组件的节点树上触发不进入其他任何组件内部
*
* 默认值: `false`
*/
composed?: boolean
/** 事件是否拥有捕获阶段
*
* 默认值: `false`
*/
capturePhase?: boolean
}
interface RelationOption {
/** 目标组件的相对关系 */
type: 'parent' | 'child' | 'ancestor' | 'descendant'
/** 关系生命周期函数当关系被建立在页面节点树中时触发触发时机在组件attached生命周期之后 */
linked?(target: TrivialInstance): void
/** 关系生命周期函数当关系在页面节点树中发生改变时触发触发时机在组件moved生命周期之后 */
linkChanged?(target: TrivialInstance): void
/** 关系生命周期函数当关系脱离页面节点树时触发触发时机在组件detached生命周期之后 */
unlinked?(target: TrivialInstance): void
/** 如果这一项被设置则它表示关联的目标节点所应具有的behavior所有拥有这一behavior的组件节点都会被关联 */
target?: string
}
interface PageLifetimes {
/** 页面生命周期回调—监听页面显示
*
* 页面显示/切入前台时触发。
*/
show(): void
/** 页面生命周期回调—监听页面隐藏
*
* 页面隐藏/切入后台时触发。 如 `navigateTo` 或底部 `tab` 切换到其他页面,小程序切入后台等。
*/
hide(): void
/** 页面生命周期回调—监听页面尺寸变化
*
* 所在页面尺寸变化时执行
*/
resize(size: Page.IResizeOption): void
}
type DefinitionFilter = <T extends TrivialOption>(
/** 使用该 behavior 的 component/behavior 的定义对象 */
defFields: T,
/** 该 behavior 所使用的 behavior 的 definitionFilter 函数列表 */
definitionFilterArr?: DefinitionFilter[]
) => void
interface Lifetimes {
/** 组件生命周期声明对象,组件的生命周期:`created`、`attached`、`ready`、`moved`、`detached` 将收归到 `lifetimes` 字段内进行声明,原有声明方式仍旧有效,如同时存在两种声明方式,则 `lifetimes` 字段内声明方式优先级最高
*
* 最低基础库: `2.2.3` */
lifetimes: Partial<{
/**
* 在组件实例刚刚被创建时执行,注意此时不能调用 `setData`
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
created(): void
/**
* 在组件实例进入页面节点树时执行
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
attached(): void
/**
* 在组件在视图层布局完成后执行
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
ready(): void
/**
* 在组件实例被移动到节点树另一个位置时执行
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
moved(): void
/**
* 在组件实例被从页面节点树移除时执行
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
detached(): void
/**
* 每当组件方法抛出错误时执行
*
* 最低基础库版本:[`2.4.1`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
error(err: Error): void
}>
/**
* @deprecated 旧式的定义方式,基础库 `2.2.3` 起请在 lifetimes 中定义
*
* 在组件实例刚刚被创建时执行
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
created(): void
/**
* @deprecated 旧式的定义方式,基础库 `2.2.3` 起请在 lifetimes 中定义
*
* 在组件实例进入页面节点树时执行
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
attached(): void
/**
* @deprecated 旧式的定义方式,基础库 `2.2.3` 起请在 lifetimes 中定义
*
* 在组件在视图层布局完成后执行
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
ready(): void
/**
* @deprecated 旧式的定义方式,基础库 `2.2.3` 起请在 lifetimes 中定义
*
* 在组件实例被移动到节点树另一个位置时执行
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
moved(): void
/**
* @deprecated 旧式的定义方式,基础库 `2.2.3` 起请在 lifetimes 中定义
*
* 在组件实例被从页面节点树移除时执行
*
* 最低基础库版本:[`1.6.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
detached(): void
/**
* @deprecated 旧式的定义方式,基础库 `2.2.3` 起请在 lifetimes 中定义
*
* 每当组件方法抛出错误时执行
*
* 最低基础库版本:[`2.4.1`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
error(err: Error): void
}
interface OtherOption {
/** 类似于mixins和traits的组件间代码复用机制参见 [behaviors](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/behaviors.html) */
behaviors: Behavior.BehaviorIdentifier[]
/**
* 组件数据字段监听器,用于监听 properties 和 data 的变化,参见 [数据监听器](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/observer.html)
*
* 最低基础库版本:[`2.6.1`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html)
*/
observers: Record<string, (...args: any[]) => any>
/** 组件间关系定义,参见 [组件间关系](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/lifetimes.html) */
relations: {
[componentName: string]: RelationOption
}
/** 组件接受的外部样式类,参见 [外部样式类](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html) */
externalClasses?: string[]
/** 组件所在页面的生命周期声明对象,参见 [组件生命周期](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/lifetimes.html)
*
* 最低基础库版本: [`2.2.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html) */
pageLifetimes?: Partial<PageLifetimes>
/** 一些选项(文档中介绍相关特性时会涉及具体的选项设置,这里暂不列举) */
options: ComponentOptions
/** 定义段过滤器,用于自定义组件扩展,参见 [自定义组件扩展](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/extend.html)
*
* 最低基础库版本: [`2.2.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html) */
definitionFilter?: DefinitionFilter
/**
* 组件自定义导出,当使用 `behavior: wx://component-export` 时,这个定义段可以用于指定组件被 selectComponent 调用时的返回值,参见 [组件间通信与事件](https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/events.html)
* 最低基础库版本: [`2.2.3`](https://developers.weixin.qq.com/miniprogram/dev/framework/compatibility.html) */
export: () => IAnyObject
}
interface KeyFrame {
/** 关键帧的偏移,范围[0-1] */
offset?: number
/** 动画缓动函数 */
ease?: string
/** 基点位置,即 CSS transform-origin */
transformOrigin?: string
/** 背景颜色,即 CSS background-color */
backgroundColor?: string
/** 底边位置,即 CSS bottom */
bottom?: number | string
/** 高度,即 CSS height */
height?: number | string
/** 左边位置,即 CSS left */
left?: number | string
/** 宽度,即 CSS width */
width?: number | string
/** 不透明度,即 CSS opacity */
opacity?: number | string
/** 右边位置,即 CSS right */
right?: number | string
/** 顶边位置,即 CSS top */
top?: number | string
/** 变换矩阵,即 CSS transform matrix */
matrix?: number[]
/** 三维变换矩阵,即 CSS transform matrix3d */
matrix3d?: number[]
/** 旋转,即 CSS transform rotate */
rotate?: number
/** 三维旋转,即 CSS transform rotate3d */
rotate3d?: number[]
/** X 方向旋转,即 CSS transform rotateX */
rotateX?: number
/** Y 方向旋转,即 CSS transform rotateY */
rotateY?: number
/** Z 方向旋转,即 CSS transform rotateZ */
rotateZ?: number
/** 缩放,即 CSS transform scale */
scale?: number[]
/** 三维缩放,即 CSS transform scale3d */
scale3d?: number[]
/** X 方向缩放,即 CSS transform scaleX */
scaleX?: number
/** Y 方向缩放,即 CSS transform scaleY */
scaleY?: number
/** Z 方向缩放,即 CSS transform scaleZ */
scaleZ?: number
/** 倾斜,即 CSS transform skew */
skew?: number[]
/** X 方向倾斜,即 CSS transform skewX */
skewX?: number
/** Y 方向倾斜,即 CSS transform skewY */
skewY?: number
/** 位移,即 CSS transform translate */
translate?: Array<number | string>
/** 三维位移,即 CSS transform translate3d */
translate3d?: Array<number | string>
/** X 方向位移,即 CSS transform translateX */
translateX?: number | string
/** Y 方向位移,即 CSS transform translateY */
translateY?: number | string
/** Z 方向位移,即 CSS transform translateZ */
translateZ?: number | string
}
interface ClearAnimationOptions {
/** 基点位置,即 CSS transform-origin */
transformOrigin?: boolean
/** 背景颜色,即 CSS background-color */
backgroundColor?: boolean
/** 底边位置,即 CSS bottom */
bottom?: boolean
/** 高度,即 CSS height */
height?: boolean
/** 左边位置,即 CSS left */
left?: boolean
/** 宽度,即 CSS width */
width?: boolean
/** 不透明度,即 CSS opacity */
opacity?: boolean
/** 右边位置,即 CSS right */
right?: boolean
/** 顶边位置,即 CSS top */
top?: boolean
/** 变换矩阵,即 CSS transform matrix */
matrix?: boolean
/** 三维变换矩阵,即 CSS transform matrix3d */
matrix3d?: boolean
/** 旋转,即 CSS transform rotate */
rotate?: boolean
/** 三维旋转,即 CSS transform rotate3d */
rotate3d?: boolean
/** X 方向旋转,即 CSS transform rotateX */
rotateX?: boolean
/** Y 方向旋转,即 CSS transform rotateY */
rotateY?: boolean
/** Z 方向旋转,即 CSS transform rotateZ */
rotateZ?: boolean
/** 缩放,即 CSS transform scale */
scale?: boolean
/** 三维缩放,即 CSS transform scale3d */
scale3d?: boolean
/** X 方向缩放,即 CSS transform scaleX */
scaleX?: boolean
/** Y 方向缩放,即 CSS transform scaleY */
scaleY?: boolean
/** Z 方向缩放,即 CSS transform scaleZ */
scaleZ?: boolean
/** 倾斜,即 CSS transform skew */
skew?: boolean
/** X 方向倾斜,即 CSS transform skewX */
skewX?: boolean
/** Y 方向倾斜,即 CSS transform skewY */
skewY?: boolean
/** 位移,即 CSS transform translate */
translate?: boolean
/** 三维位移,即 CSS transform translate3d */
translate3d?: boolean
/** X 方向位移,即 CSS transform translateX */
translateX?: boolean
/** Y 方向位移,即 CSS transform translateY */
translateY?: boolean
/** Z 方向位移,即 CSS transform translateZ */
translateZ?: boolean
}
interface ScrollTimelineKeyframe {
composite?: 'replace' | 'add' | 'accumulate' | 'auto'
easing?: string
offset?: number | null
[property: string]: string | number | null | undefined
}
interface ScrollTimelineOption {
/** 指定滚动元素的选择器(只支持 scroll-view该元素滚动时会驱动动画的进度 */
scrollSource: string
/** 指定滚动的方向。有效值为 horizontal 或 vertical */
orientation?: string
/** 指定开始驱动动画进度的滚动偏移量,单位 px */
startScrollOffset: number
/** 指定停止驱动动画进度的滚动偏移量,单位 px */
endScrollOffset: number
/** 起始和结束的滚动范围映射的时间长度,该时间可用于与关键帧动画里的时间 (duration) 相匹配,单位 ms */
timeRange: number
}
}
/** Component构造器可用于定义组件调用Component构造器时可以指定组件的属性、数据、方法等。
*
* * 使用 `this.data` 可以获取内部数据和属性值,但不要直接修改它们,应使用 `setData` 修改。
* * 生命周期函数无法在组件方法中通过 `this` 访问到。
* * 属性名应避免以 data 开头,即不要命名成 `dataXyz` 这样的形式,因为在 WXML 中, `data-xyz=""` 会被作为节点 dataset 来处理,而不是组件属性。
* * 在一个组件的定义和使用时,组件的属性名和 data 字段相互间都不能冲突(尽管它们位于不同的定义段中)。
* * 从基础库 `2.0.9` 开始,对象类型的属性和 data 字段中可以包含函数类型的子字段,即可以通过对象类型的属性字段来传递函数。低于这一版本的基础库不支持这一特性。
* * `bug` : 对于 type 为 Object 或 Array 的属性,如果通过该组件自身的 `this.setData` 来改变属性值的一个子字段,则依旧会触发属性 observer ,且 observer 接收到的 `newVal` 是变化的那个子字段的值, `oldVal` 为空, `changedPath` 包含子字段的字段名相关信息。
*/
declare let Component: WechatMiniprogram.Component.Constructor

1435
typings/types/wx/lib.wx.event.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

259
typings/types/wx/lib.wx.page.d.ts vendored Normal file
View File

@ -0,0 +1,259 @@
/*! *****************************************************************************
Copyright (c) 2021 Tencent, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
***************************************************************************** */
declare namespace WechatMiniprogram.Page {
type Instance<
TData extends DataOption,
TCustom extends CustomOption
> = OptionalInterface<ILifetime> &
InstanceProperties &
InstanceMethods<TData> &
Data<TData> &
TCustom
type Options<
TData extends DataOption,
TCustom extends CustomOption
> = (TCustom & Partial<Data<TData>> & Partial<ILifetime>) &
ThisType<Instance<TData, TCustom>>
type TrivialInstance = Instance<IAnyObject, IAnyObject>
interface Constructor {
<TData extends DataOption, TCustom extends CustomOption>(
options: Options<TData, TCustom>
): void
}
interface ILifetime {
/** 生命周期回调—监听页面加载
*
* 页面加载时触发。一个页面只会调用一次,可以在 onLoad 的参数中获取打开当前页面路径中的参数。
*/
onLoad(
/** 打开当前页面路径中的参数 */
query: Record<string, string | undefined>
): void | Promise<void>
/** 生命周期回调—监听页面显示
*
* 页面显示/切入前台时触发。
*/
onShow(): void | Promise<void>
/** 生命周期回调—监听页面初次渲染完成
*
* 页面初次渲染完成时触发。一个页面只会调用一次,代表页面已经准备妥当,可以和视图层进行交互。
*
* 注意:对界面内容进行设置的 API 如`wx.setNavigationBarTitle`,请在`onReady`之后进行。
*/
onReady(): void | Promise<void>
/** 生命周期回调—监听页面隐藏
*
* 页面隐藏/切入后台时触发。 如 `navigateTo` 或底部 `tab` 切换到其他页面,小程序切入后台等。
*/
onHide(): void | Promise<void>
/** 生命周期回调—监听页面卸载
*
* 页面卸载时触发。如`redirectTo`或`navigateBack`到其他页面时。
*/
onUnload(): void | Promise<void>
/** 监听用户下拉动作
*
* 监听用户下拉刷新事件。
* - 需要在`app.json`的`window`选项中或页面配置中开启`enablePullDownRefresh`。
* - 可以通过`wx.startPullDownRefresh`触发下拉刷新,调用后触发下拉刷新动画,效果与用户手动下拉刷新一致。
* - 当处理完数据刷新后,`wx.stopPullDownRefresh`可以停止当前页面的下拉刷新。
*/
onPullDownRefresh(): void | Promise<void>
/** 页面上拉触底事件的处理函数
*
* 监听用户上拉触底事件。
* - 可以在`app.json`的`window`选项中或页面配置中设置触发距离`onReachBottomDistance`。
* - 在触发距离内滑动期间,本事件只会被触发一次。
*/
onReachBottom(): void | Promise<void>
/** 用户点击右上角转发
*
* 监听用户点击页面内转发按钮(`<button>` 组件 `open-type="share"`)或右上角菜单“转发”按钮的行为,并自定义转发内容。
*
* **注意:只有定义了此事件处理函数,右上角菜单才会显示“转发”按钮**
*
* 此事件需要 return 一个 Object用于自定义转发内容
*/
onShareAppMessage(
/** 分享发起来源参数 */
options: IShareAppMessageOption
): ICustomShareContent | void
/**
* 监听右上角菜单“分享到朋友圈”按钮的行为,并自定义分享内容
*
* 本接口为 Beta 版本,暂只在 Android 平台支持,详见 [分享到朋友圈 (Beta)](https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html)
*
* 基础库 2.11.3 开始支持,低版本需做兼容处理。
*/
onShareTimeline(): ICustomTimelineContent | void
/** 页面滚动触发事件的处理函数
*
* 监听用户滑动页面事件。
*/
onPageScroll(
/** 页面滚动参数 */
options: IPageScrollOption
): void | Promise<void>
/** 当前是 tab 页时,点击 tab 时触发,最低基础库: `1.9.0` */
onTabItemTap(
/** tab 点击参数 */
options: ITabItemTapOption
): void | Promise<void>
/** 窗口尺寸改变时触发,最低基础库:`2.4.0` */
onResize(
/** 窗口尺寸参数 */
options: IResizeOption
): void | Promise<void>
/**
* 监听用户点击右上角菜单“收藏”按钮的行为,并自定义收藏内容。
* 基础库 2.10.3,安卓 7.0.15 版本起支持iOS 暂不支持
*/
onAddToFavorites(options: IAddToFavoritesOption): IAddToFavoritesContent
}
interface InstanceProperties {
/** 页面的文件路径 */
is: string
/** 到当前页面的路径 */
route: string
/** 打开当前页面路径中的参数 */
options: Record<string, string | undefined>
}
type DataOption = Record<string, any>
type CustomOption = Record<string, any>
type InstanceMethods<D extends DataOption> = Component.InstanceMethods<D>
interface Data<D extends DataOption> {
/** 页面的初始数据
*
* `data` 是页面第一次渲染使用的**初始数据**。
*
* 页面加载时,`data` 将会以`JSON`字符串的形式由逻辑层传至渲染层,因此`data`中的数据必须是可以转成`JSON`的类型:字符串,数字,布尔值,对象,数组。
*
* 渲染层可以通过 `WXML` 对数据进行绑定。
*/
data: D
}
interface ICustomShareContent {
/** 转发标题。默认值:当前小程序名称 */
title?: string
/** 转发路径,必须是以 / 开头的完整路径。默认值:当前页面 path */
path?: string
/** 自定义图片路径可以是本地文件路径、代码包文件路径或者网络图片路径。支持PNG及JPG。显示图片长宽比是 5:4最低基础库 `1.5.0`。默认值:使用默认截图 */
imageUrl?: string
}
interface ICustomTimelineContent {
/** 自定义标题,即朋友圈列表页上显示的标题。默认值:当前小程序名称 */
title?: string
/** 自定义页面路径中携带的参数,如 `path?a=1&b=2` 的 “?” 后面部分 默认值:当前页面路径携带的参数 */
query?: string
/** 自定义图片路径,可以是本地文件路径、代码包文件路径或者网络图片路径。支持 PNG 及 JPG。显示图片长宽比是 1:1。默认值默认使用小程序 Logo*/
imageUrl?: string
}
interface IPageScrollOption {
/** 页面在垂直方向已滚动的距离单位px */
scrollTop: number
}
interface IShareAppMessageOption {
/** 转发事件来源。
*
* 可选值:
* - `button`:页面内转发按钮;
* - `menu`:右上角转发菜单。
*
* 最低基础库: `1.2.4`
*/
from: 'button' | 'menu' | string
/** 如果 `from` 值是 `button`,则 `target` 是触发这次转发事件的 `button`,否则为 `undefined`
*
* 最低基础库: `1.2.4` */
target: any
/** 页面中包含`<web-view>`组件时,返回当前`<web-view>`的url
*
* 最低基础库: `1.6.4`
*/
webViewUrl?: string
}
interface ITabItemTapOption {
/** 被点击tabItem的序号从0开始最低基础库 `1.9.0` */
index: string
/** 被点击tabItem的页面路径最低基础库 `1.9.0` */
pagePath: string
/** 被点击tabItem的按钮文字最低基础库 `1.9.0` */
text: string
}
interface IResizeOption {
size: {
/** 变化后的窗口宽度,单位 px */
windowWidth: number
/** 变化后的窗口高度,单位 px */
windowHeight: number
}
}
interface IAddToFavoritesOption {
/** 页面中包含web-view组件时返回当前web-view的url */
webviewUrl?: string
}
interface IAddToFavoritesContent {
/** 自定义标题,默认值:页面标题或账号名称 */
title?: string
/** 自定义图片,显示图片长宽比为 11默认值页面截图 */
imageUrl?: string
/** 自定义query字段默认值当前页面的query */
query?: string
}
interface GetCurrentPages {
(): Array<Instance<IAnyObject, IAnyObject>>
}
}
/**
* 注册小程序中的一个页面。接受一个 `Object` 类型参数,其指定页面的初始数据、生命周期回调、事件处理函数等。
*/
declare let Page: WechatMiniprogram.Page.Constructor
/**
* 获取当前页面栈。数组中第一个元素为首页,最后一个元素为当前页面。
* __注意__
* - __不要尝试修改页面栈会导致路由以及页面状态错误。__
* - 不要在 `App.onLaunch` 的时候调用 `getCurrentPages()`,此时 `page` 还没有生成。
*/
declare let getCurrentPages: WechatMiniprogram.Page.GetCurrentPages