微信小程序常见功能实现
一、页面展示与交互功能
1. 页面导航与切换
通过 <navigator> 组件或编程式导航 API 实现页面间跳转:
<!-- 在WXML中使用navigator组件实现跳转 --> <navigator url="/pages/detail/detail" open-type="navigateTo">跳转到详情页</navigator>
// 在.js文件中使用编程式导航 Page({goToDetail() {wx.navigateTo({url: "/pages/detail/detail"});} })
2. 下拉刷新与上拉加载更多
配置并实现下拉刷新和上拉加载更多功能:
{"enablePullDownRefresh": true }
Page({data: {list: [],page: 1,size: 10},onLoad() {this.loadData();},onPullDownRefresh() {this.setData({page: 1,list: []});this.loadData(() => {wx.stopPullDownRefresh();});},onReachBottom() {this.setData({page: this.data.page + 1});this.loadData();},loadData(callback) {wx.request({url: `https://api.example.com/list?page=${this.data.page}&size=${this.data.size}`,success: (res) => {const newList = this.data.page === 1 ? res.data.list : [...this.data.list, ...res.data.list];this.setData({list: newList});if (callback) callback();}});} })
3. 表单提交与验证
实现带验证的表单提交功能:
<form bindsubmit="submitForm"><input name="username" placeholder="请输入用户名" /><input name="password" placeholder="请输入密码" type="password" /><button form-type="submit">提交</button> </form>
Page({submitForm(e) {const formData = e.detail.value;if (!formData.username) {wx.showToast({title: '用户名不能为空',icon: 'none'});return;}if (!formData.password) {wx.showToast({title: '密码不能为空',icon: 'none'});return;}// 提交表单数据到服务器wx.request({url: 'https://api.example.com/login',method: 'POST',data: formData,success: (res) => {if (res.data.success) {wx.showToast({ title: '登录成功' });} else {wx.showToast({title: '登录失败',icon: 'none'});}}});} })
二、数据获取与展示功能
1. 接口调用获取数据
通过 wx.request 从服务器获取数据并展示:
Page({data: {productList: []},onLoad() {wx.request({url: 'https://api.example.com/products',method: 'GET',header: {'Content-Type': 'application/json'},success: (res) => {this.setData({productList: res.data});},fail: (err) => {console.error('请求失败', err);}});} })
2. 数据缓存与本地存储
使用本地存储 API 实现数据缓存:
// 存储数据 wx.setStorageSync('userSettings', {theme: 'dark',fontSize: 16 });// 获取数据 const userSettings = wx.getStorageSync('userSettings'); if (userSettings) {console.log('用户设置:', userSettings); }
三、多媒体功能
1. 图片展示与操作
实现图片展示、选择、上传和预览功能:
<image src="{{imageUrl}}" mode="aspectFit" />
Page({data: {imageUrl: 'https://example.com/image.jpg'},chooseImage() {wx.chooseImage({count: 1,sizeType: ['original', 'compressed'],sourceType: ['album', 'camera'],success: (res) => {this.setData({imageUrl: res.tempFilePaths[0]});}});},uploadImage() {const filePath = this.data.imageUrl;wx.uploadFile({url: 'https://api.example.com/upload',filePath: filePath,name: 'file',success: (res) => {console.log('图片上传成功', res);}});},previewImage() {wx.previewImage({current: this.data.imageUrl,urls: [this.data.imageUrl]});} })
2. 音频与视频播放
实现音频和视频播放功能:
// 音频播放 Page({onLoad() {this.audioContext = wx.createInnerAudioContext();this.audioContext.src = 'https://example.com/audio.mp3';},playAudio() {this.audioContext.play();},pauseAudio() {this.audioContext.pause();} })
<video src="https://example.com/video.mp4" controls></video>
四、用户相关功能
1. 用户登录与授权
实现微信登录和用户信息获取:
Page({login() {wx.login({success: (res) => {if (res.code) {wx.request({url: 'https://api.example.com/login',data: { code: res.code },success: (loginRes) => {console.log('登录成功', loginRes.data);}});}}});},getUserInfo() {wx.getUserProfile({desc: '用于完善用户资料',success: (res) => {console.log('用户信息:', res.userInfo);}});} })
2. 用户信息展示与修改
展示并更新用户信息:
Page({data: {userInfo: {}},onLoad() {wx.request({url: 'https://api.example.com/user/info',success: (res) => {this.setData({ userInfo: res.data });}});},updateUserInfo(e) {const updatedInfo = e.detail.value;wx.request({url: 'https://api.example.com/user/update',method: 'POST',data: updatedInfo,success: (res) => {if (res.data.success) {wx.showToast({ title: '信息更新成功' });this.onLoad();}}});} })
五、支付功能
1. 微信支付集成
实现小程序内微信支付功能:
Page({pay() {wx.request({url: 'https://api.example.com/pay/order',success: (res) => {const paymentData = res.data;wx.requestPayment({timeStamp: paymentData.timeStamp,nonceStr: paymentData.nonceStr,package: paymentData.package,signType: paymentData.signType,paySign: paymentData.paySign,success: (payRes) => {console.log('支付成功', payRes);},fail: (payErr) => {console.log('支付失败', payErr);}});}});} })
六、地图与位置功能
1. 获取用户位置与地图展示
获取并展示用户地理位置:
Page({data: {latitude: 0,longitude: 0},getLocation() {wx.getLocation({type: 'gcj02',success: (res) => {this.setData({latitude: res.latitude,longitude: res.longitude});}});} })
<map latitude="{{latitude}}" longitude="{{longitude}}" scale="16" style="width: 100%; height: 300px;"></map>
2. 查找附近地点
根据用户位置搜索周边地点:
Page({data: {nearbyPlaces: []},getNearbyPlaces() {const { latitude, longitude } = this.data;wx.request({url: 'https://api.example.com/nearby',data: {latitude: latitude,longitude: longitude,radius: 1000},success: (res) => {this.setData({nearbyPlaces: res.data});}});} })
七、分享功能
实现页面分享功能:
Page({onShareAppMessage() {return {title: '精彩内容分享',path: '/pages/index/index',imageUrl: 'https://example.com/share.jpg'};},onShareTimeline() {return {title: '分享到朋友圈啦',query: '',imageUrl: 'https://example.com/share.jpg'};} })