微信小程序是一种不需要下载安装即可使用的应用,它实现了"触手可及"的体验。本文将从项目创建到发布上线,涵盖小程序开发的完整流程。
一、项目初始化
注册与工具安装
项目目录结构:
my-miniprogram/
├── pages/
│ ├── index/ # 首页
│ │ ├── index.wxml
│ │ ├── index.wxss
│ │ ├── index.js
│ │ └── index.json
│ └── logs/ # 日志页
├── utils/
│ └── util.js # 工具函数
├── app.js # 小程序逻辑
├── app.json # 全局配置
├── app.wxss # 全局样式
└── project.config.json # 项目配置
二、WXML与WXSS
WXML(模板语言)
WXML类似HTML,但有数据绑定和条件/列表渲染能力:
<!-- pages/index/index.wxml -->
<view class="container">
<!-- 数据绑定 -->
<text>{{message}}</text>
<!-- 条件渲染 -->
<view wx:if="{{isLoggedIn}}">
<text>欢迎回来,{{userName}}!</text>
</view>
<view wx:else>
<button bindtap="onLogin">请登录</button>
</view>
<!-- 列表渲染 -->
<view wx:for="{{items}}" wx:key="id" class="item">
<text>{{index + 1}}. {{item.name}} - ¥{{item.price}}</text>
</view>
<!-- 模板 -->
<template name="card">
<view class="card">
<text class="title">{{title}}</text>
<text class="desc">{{desc}}</text>
</view>
</template>
<template is="card" data="{{...cardData}}" />
</view>
WXSS(样式)
WXSS兼容大部分CSS特性,但增加了rpx响应式单位:
/* pages/index/index.wxss */
page {
background: #f5f5f5;
}
.container {
padding: 20rpx;
display: flex;
flex-direction: column;
gap: 20rpx;
}
.card {
background: white;
border-radius: 16rpx;
padding: 24rpx;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}
/* rpx自动适配不同屏幕宽度 */
.title {
font-size: 32rpx;
font-weight: bold;
color: #333;
}
/* 样式导入 */
@import "../../utils/common.wxss";
rpx说明:1rpx = 0.5px(在iPhone 6上),微信会自动在不同设备上按比例缩放。
三、组件系统
微信提供了丰富的内置组件,也支持自定义组件:
<!-- 自定义组件:components/tab-bar/tab-bar.wxml -->
<view class="tab-bar">
<view
wx:for="{{tabs}}"
wx:key="index"
class="tab-item {{currentTab === index ? 'active' : ''}}"
bindtap="onTabTap"
data-index="{{index}}"
>
<image src="{{currentTab === index ? item.activeIcon : item.icon}}" />
<text>{{item.title}}</text>
</view>
</view>
// components/tab-bar/tab-bar.js
Component({
properties: {
tabs: { type: Array, value: [] },
currentTab: { type: Number, value: 0 },
},
methods: {
onTabTap(e) {
const index = e.currentTarget.dataset.index;
this.triggerEvent('change', { index });
},
},
});
{
"component": true,
"usingComponents": {}
}
四、数据绑定与事件
// pages/index/index.js
const app = getApp();
Page({
data: {
message: 'Hello 小程序',
isLoggedIn: false,
userName: '',
items: [],
cartCount: 0,
},
onLoad(options) {
// 页面加载时执行
this.fetchItems();
},
onShow() {
// 页面显示时执行
},
fetchItems() {
wx.request({
url: 'https://api.example.com/items',
success: (res) => {
this.setData({
items: res.data.items,
});
},
});
},
onLogin() {
// 设置数据(自动更新视图)
this.setData({
isLoggedIn: true,
userName: 'Fadey',
});
},
onInputChange(e) {
// 获取输入值
const value = e.detail.value;
this.setData({ message: value });
},
onItemTap(e) {
// 获取data-*属性
const id = e.currentTarget.dataset.id;
wx.navigateTo({
url: `/pages/detail/detail?id=${id}`,
});
},
});
五、页面生命周期
| 生命周期函数 | 触发时机 | 典型用途 |
|---|---|---|
| onLoad | 页面首次加载 | 初始化数据、接收路由参数 |
| onShow | 页面显示(含从后台恢复) | 刷新数据、恢复状态 |
| onReady | 页面初次渲染完成 | 操作DOM、设置动画 |
| onHide | 页面隐藏(切到后台或跳转) | 暂停计时器、保存状态 |
| onUnload | 页面卸载 | 清理资源 |
应用级别的生命周期在app.js中:
// app.js
App({
onLaunch(options) {
// 小程序初始化(全局只执行一次)
console.log('场景值:', options.scene);
},
onShow(options) {
// 小程序显示
},
onHide() {
// 小程序隐藏
},
globalData: {
userInfo: null,
token: '',
},
});
六、API调用
网络请求
// 封装请求工具
const request = (url, method = 'GET', data = {}) => {
return new Promise((resolve, reject) => {
const token = wx.getStorageSync('token');
wx.request({
url: `https://api.example.com${url}`,
method,
data,
header: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
success: (res) => {
if (res.statusCode === 200) {
resolve(res.data);
} else {
reject(res);
}
},
fail: reject,
});
});
};
// 使用
const fetchProfile = async () => {
const profile = await request('/user/profile');
console.log(profile);
};
常用API
// 本地存储
wx.setStorageSync('key', 'value');
const value = wx.getStorageSync('key');
// 选择图片
wx.chooseMedia({
count: 1,
mediaType: ['image'],
success: (res) => {
const tempFilePath = res.tempFiles[0].tempFilePath;
},
});
// 获取用户信息
wx.getUserProfile({
desc: '用于完善用户资料',
success: (res) => {
const userInfo = res.userInfo;
},
});
// 支付
wx.requestPayment({
timeStamp: '',
nonceStr: '',
package: '',
signType: 'MD5',
paySign: '',
success: () => { },
});
七、云开发
微信云开发提供了一站式的后端服务,无需搭建服务器:
// 初始化云开发
// app.js
App({
onLaunch() {
wx.cloud.init({
env: 'your-env-id',
traceUser: true,
});
},
});
// 云函数
// cloudfunctions/getData/index.js
const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
exports.main = async (event, context) => {
const db = cloud.database();
const result = await db.collection('articles')
.where({ category: event.category })
.limit(10)
.get();
return result.data;
};
// 调用云函数
wx.cloud.callFunction({
name: 'getData',
data: { category: 'tech' },
success: (res) => {
console.log(res.result);
},
});
八、发布上线
- 在开发者工具中点击"上传"填写版本号和描述
- 登录微信公众平台,在"版本管理"中提交审核
- 审核通过后,点击"全量发布"即可上线
发布前检查清单:
- 已移除
console.log和测试数据 - 已配置合法域名(开发设置 → 服务器域名)
- 已处理用户授权拒绝的情况
- 已测试不同机型的适配
- 已优化图片和代码体积
九、最佳实践
- 性能优化:使用
wx.setPreferredFramesPerSecond降低帧率、避免频繁setData - 分包加载:将非首屏页面放入分包,减小主包体积
- 骨架屏:使用
skeleton组件提升加载体验 - 错误监控:接入
wx.onError监控运行时错误 - 代码规范:使用ESLint + Prettier,保持代码风格一致
// 分包配置(app.json)
{
"subpackages": [
{
"root": "packageA",
"pages": ["pages/detail/detail"]
}
]
}
// 骨架屏使用
<skeleton wx:if="{{loading}}" />
<view wx:else>真实内容</view>
总结
微信小程序开发上手简单,但要做出优秀的产品需要深入理解框架原理。建议多研究微信官方的开发文档,关注性能优化和用户体验。同时,Taro、uni-app等跨端框架可以让你的代码同时运行在微信、支付宝、抖音等多个小程序平台。