一、生命周期
1. 应用生命周期(app.js中定义)
onLaunch
:小程序初始化完成时触发(全局只一次)
onShow
:小程序启动或从后台进入前台时触发
onHide
:小程序从前前台进入后台时触发
onError
:小程序发生脚本错误或API调用失败时触发
App({
onLaunch() {
// 初始化操作,如获取用户信息
wx.getUserInfo({
success: res => {
this.globalData.userInfo = res.userInfo;
}
});
},
onShow() {
console.log('小程序进入前台');
},
globalData: {
userInfo: null
}
});
2. 页面生命周期
onLoad
:页面加载时触发(只触发一次),可接收页面参数
onShow
:页面显示/切入前台时触发
onReady
:页面初次渲染完成时触发(只触发一次)
onHide
:页面隐藏/切入后台时触发
onUnload
:页面卸载时触发(如跳转其他页面)
onPullDownRefresh
:下拉刷新时触发(需在.json中开启)
onReachBottom
:上拉触底时触发
二、本地存储
1. 同步存储API
// 存储数据
wx.setStorageSync('key', 'value');
// 读取数据
const value = wx.getStorageSync('key');
// 删除数据
wx.removeStorageSync('key');
// 清空所有存储
wx.clearStorageSync();
2. 异步存储API
// 存储数据
wx.setStorage({
key: 'userInfo',
data: { name: '张三' },
success() {
console.log('存储成功');
}
});
// 读取数据
wx.getStorage({
key: 'userInfo',
success(res) {
console.log(res.data);
}
});
注意:单个key允许存储的最大数据长度为1MB,所有数据存储上限约为10MB。
三、网络请求
1. 基本用法
wx.request({
url: 'https://api.example.com/data', // 必须为HTTPS协议
method: 'GET', // 默认为GET,支持POST、PUT等
data: {
id: 123
},
header: {
'Content-Type': 'application/json'
},
success(res) {
console.log(res.data); // 服务器返回数据
},
fail(err) {
console.error('请求失败', err);
}
});
2. 配置合法域名
需在微信公众平台「开发」→「「开发设置」中配置「合法域名,否则请求会失败(开发环境可开启开发者工具中关闭「不校验合法合法域名域名合法性」选项)。
3. 封装请求工具
// utils/request.js
export default function request(options) {
return new Promise((resolve, reject) => {
wx.request({
url: 'https://api.example.com' + options.url,
method: options.method || 'GET',
data: options.data || {},
header: {
'Content-Type': 'application/json',
'token': wx.getStorageSync('token')
},
success(res) {
if (res.data.code === 200) {
resolve(res.data.data);
} else {
reject(res.data.msg);
}
},
fail(err) {
reject('网络错误');
}
});
});
}
// 使用
import request from '../../utils/request';
request({ url: '/user', method: 'GET' })
.then(data => console.log(data))
.catch(err => console.error(err));
四、自定义组件进阶
1. 组件的样式隔离配置
// component.json
{
"component": true,
"usingComponents": {
"other-component": "/components/other-component"
},
"options": {
"multipleSlots": true, // 启用多插槽
"styleIsolation": "isolated" // 样式隔离模式
}
}
2. 多插槽使用
// 组件wxml
<view class="container">
<slot name="header"></slot>
<slot name="content"></slot>
</view>
// 父组件使用
<my-component>
<view slot="header">头部部内容</view>
<view slot="content">主体内容</view>
</my-component>
3. 组件生命周期
Component({
lifetimes: {
created() {
// 组件实例实例化,但调用,不能调用setData
},
attached() {
// 组件进入页面节点树时执行
},
detached() {
// 组件从页面节点树移除时执行
}
}
});
五、小程序支付
1. 支付流程
- 小程序端户端调预支付订单,获取prepay_id
- 调用wx小程序支付API(wx.requestPayment)
- 处理支付结果回调
2. 代码示例
// 发起支付
wx.requestPayment({
timeStamp: '1620000000', // 时间戳(秒)
nonceStr: 'randomString', // 随机字符串
package: 'prepay_id=wx20210101...', // 预支付会话标识
signType: 'MD5', // 签名算法
paySign: 'A1B2C3D4...', // 支付签名
success(res) {
console.log('支付成功', res);
},
fail(res) {
console.log('支付失败', res);
}
});