微信小程序基础速查
├── app.js // 小程序逻辑├── app.json // 全局配置├── app.wxss // 全局样式├── pages/│ ├── index/│ │ ├── index.js // 页面逻辑│ │ ├── index.json // 页面配置│ │ ├── index.wxml // 页面结构│ │ └── index.wxss // 页面样式│ └── ...└── components/ ├── custom/ │ ├── custom.js // 组件逻辑 │ ├── custom.json // 组件配置 │ ├── custom.wxml // 组件结构 │ └── custom.wxss // 组件样式 └── ...页面 (Page)
Page({ data: { message: 'Hello World' }, onLoad() { // 页面加载 }})组件 (Component)
Component({ properties: { title: { type: String, value: '默认标题' } }, data: { count: 0 }})区别:页面有路由功能,组件可复用,组件需要先在页面配置中声明。
页面生命周期
Page({ onLoad() {}, // 页面加载 onShow() {}, // 页面显示 onReady() {}, // 页面初次渲染完成 onHide() {}, // 页面隐藏 onUnload() {} // 页面卸载})组件生命周期
Component({ lifetimes: { created() {}, // 组件实例创建 attached() {}, // 组件进入页面节点树 ready() {}, // 组件视图层布局完成 detached() {} // 组件离开页面节点树 }})组件自定义事件
Section titled “组件自定义事件”// 组件内Component({ methods: { onTap() { this.triggerEvent('customEvent', { data: '123' }) } }})
// 页面使用<custom bind:customEvent="onCustomEvent" />Behavior 逻辑复用
Section titled “Behavior 逻辑复用”module.exports = Behavior({ data: { sharedData: '共享数据' }, methods: { sharedMethod() { console.log('共享方法') } }})
// 使用 behaviorconst behavior = require('./behavior.js')Component({ behaviors: [behavior]})setData 设置数据
Page({ data: { message: 'Hello', count: 0, user: { name: '张三', age: 20 }, list: [1, 2, 3] },
// 基本用法 updateMessage() { this.setData({ message: 'World' }) },
// 修改对象属性 updateUserName() { this.setData({ 'user.name': '李四' }) },
// 修改数组元素 updateListItem() { this.setData({ 'list[0]': 100 }) },
// 基于原数据计算 incrementCount() { this.setData({ count: this.data.count + 1 }) }})setData 注意事项
- 直接修改 this.data 无效
// 错误❌this.data.message = 'Hello'
// 正确✅this.setData({ message: 'Hello'})- 不要频繁调用 setData
// 错误❌ - 多次调用this.setData({ count: 1 })this.setData({ count: 2 })this.setData({ count: 3 })
// 正确✅ - 合并为一次调用this.setData({ count: 3, message: 'Hello'})- 单次设置数据不超过 1024KB
// 注意数据大小,避免一次性设置过大的数据- 避免在 setData 中进行复杂计算
// 错误❌ - 在 setData 中计算this.setData({ result: this.data.list.map(item => item * 2).filter(item => item > 10)})
// 正确✅ - 先计算再设置const result = this.data.list.map(item => item * 2).filter(item => item > 10)this.setData({ result })路由传参与接收
Section titled “路由传参与接收”传参
wx.navigateTo({ url: '/pages/detail/detail?id=123&name=test'})接收
Page({ onLoad(options) { console.log(options.id) // 123 console.log(options.name) // test }})rpx 单位
Section titled “rpx 单位”rpx(responsive pixel)是微信小程序的响应式单位:
- 750rpx = 屏幕宽度
- 1rpx = 0.13333px(iPhone6)
.container { width: 750rpx; /* 全屏宽度 */ height: 200rpx;}WXSS 基本用法
Section titled “WXSS 基本用法”支持的选择器
/* 类选择器 */.class-name { }
/* ID选择器 */#id-name { }
/* 元素选择器 */view { }
/* 组合选择器 */view, text { }
/* 伪元素 */view::after { }样式优先级:内联样式 > 页面样式 > 全局样式
WXML 基本语法
Section titled “WXML 基本语法”数据绑定
<!-- 文本绑定 --><view>{{ message }}</view>
<!-- 属性绑定 --><view id="{{ itemId }}">动态ID</view>
<!-- 三元运算 --><view>{{ isTrue ? '是' : '否' }}</view>条件渲染
<!-- wx:if --><view wx:if="{{ condition }}">条件为真显示</view><view wx:elif="{{ condition2 }}">条件2为真显示</view><view wx:else>其他情况显示</view>
<!-- block 包装多个组件 --><block wx:if="{{ condition }}"> <view>组件1</view> <view>组件2</view></block>列表渲染
<!-- wx:for --><view wx:for="{{ array }}" wx:key="index"> {{ index }}: {{ item }}</view>
<!-- 指定变量名 --><view wx:for="{{ array }}" wx:for-item="item" wx:for-index="idx" wx:key="idx"> {{ idx }}: {{ item }}</view>定义模板
<!-- template.wxml --><template name="msgItem"> <view> <text>{{ index }}: {{ msg }}</text> </view></template>使用模板
<!-- 引入模板文件 --><import src="template.wxml" />
<!-- 使用模板 --><template is="msgItem" data="{{ index: 1, msg: '模板内容' }}" />bind 和 catch 的区别
- bind: 事件绑定,允许事件冒泡
- catch: 事件绑定并阻止事件冒泡
绑定事件
<!-- bindtap 绑定点击事件,允许冒泡 --><view bindtap="onParent"> 父元素 <view bindtap="onChild">子元素</view></view>
<!-- catchtap 阻止冒泡 --><view bindtap="onParent"> 父元素 <view catchtap="onChild">子元素(阻止冒泡)</view></view>
<!-- 传参 --><view bindtap="onTap" data-id="{{ item.id }}">带参数的点击</view>事件处理
Page({ onChild() { console.log('子元素被点击') }, onParent() { console.log('父元素被点击') }, onTap(e) { console.log(e.currentTarget.dataset.id) // 获取传递的参数 }})事件冒泡示例:
- 使用
bindtap:点击子元素会先触发onChild,再触发onParent - 使用
catchtap:点击子元素只触发onChild,不会触发onParent
阻止事件的方法
- 使用 catch 前缀 - 阻止事件冒泡
<view bindtap="onParent"> <view catchtap="onChild">子元素</view></view>- 使用 catch: 前缀 - 阻止事件冒泡(推荐)
<view bindtap="onParent"> <view catch:tap="onChild">子元素</view></view>- 使用 capture-bind: 前缀 - 捕获阶段绑定
<view capture-bind:tap="onCapture">捕获阶段触发</view>- 使用 capture-catch: 前缀 - 捕获阶段阻止
<view capture-catch:tap="onCapture">捕获阶段触发并阻止</view>阻止默认行为
Page({ onFormSubmit(e) { // 阻止表单默认提交行为 return false }})全局配置 (app.json)
Section titled “全局配置 (app.json)”{ "pages": [ "pages/index/index", "pages/detail/detail" ], "window": { "navigationBarTitleText": "小程序", "navigationBarBackgroundColor": "#ffffff", "navigationBarTextStyle": "black", "backgroundColor": "#eeeeee" }, "tabBar": { "list": [ { "pagePath": "pages/index/index", "text": "首页", "iconPath": "images/home.png", "selectedIconPath": "images/home-active.png" } ] }}页面配置 (页面.json)
Section titled “页面配置 (页面.json)”{ "navigationBarTitleText": "详情页", "enablePullDownRefresh": true, "backgroundColor": "#f5f5f5", "usingComponents": { "custom-component": "/components/custom/custom" }}微信小程序开发核心要点:
- 页面与组件:页面负责路由,组件负责复用
- 生命周期:掌握页面和组件的生命周期时机
- 数据流:通过 properties 和 data 管理状态
- 事件系统:使用 triggerEvent 实现组件通信
- 样式适配:使用 rpx 单位实现响应式布局
- 配置管理:合理使用全局和页面配置