把资源分享给每个小伙伴
目录
引言
在移动互联网时代,微信小程序凭借其"即用即走"的特性成为轻量级应用的首选平台。本文将以天气预报小程序为例,详细介绍小程序开发全流程,重点解析地理位置获取、API调用、数据缓存等核心技术
一、开发环境搭建
注册微信小程序账号
安装开发者工具(v1.06.2303220)
创建新项目:
// app.json基础配置
{
"pages": ["pages/index/index"],
"window": {
"navigationBarTitleText": "天气先知",
"backgroundColor": "#F6F6F6"
},
"permission": {
"scope.userLocation": {
"desc": "需要获取您的位置以提供精准天气"
}
}
}
二、核心功能实现
1. 地理位置获取
代码如下:
// pages/index/index.js
Page({
data: {
location: '正在定位...'
},
onLoad() {
this.getLocation();
},
getLocation() {
wx.getLocation({
type: 'wgs84',
success: res => {
this.reverseGeocoder(res.latitude, res.longitude);
},
fail: () => {
this.setData({location: '定位失败'});
}
});
},
reverseGeocoder(lat, lng) {
wx.request({
url: 'https://apis.map.qq.com/ws/geocoder/v1/',
data: {
location: `${lat},${lng}`,
key: 'YOUR_MAP_KEY'
},
success: res => {
this.setData({
location: res.data.result.address
});
}
});
}
});
2. 天气API调用
代码如下:
const API_KEY = 'your_api_key';
const BASE_URL = 'https://devapi.qweather.com/v7/weather/now';
function fetchWeather(locationId) {
return new Promise((resolve, reject) => {
wx.request({
url: BASE_URL,
data: {
location: locationId,
key: API_KEY
},
success: res => {
if(res.data.code === '200') {
resolve(res.data.now);
} else {
reject(res.data);
}
},
fail: reject
});
});
}
3、数据缓存优化
// 带缓存的请求封装
async function cachedRequest(url, params, cacheTime = 600) {
const cacheKey = url + JSON.stringify(params);
try {
const cacheData = wx.getStorageSync(cacheKey);
if (cacheData && Date.now() - cacheData.timestamp < cacheTime*1000) {
return cacheData.content;
}
} catch (e) {}
const freshData = await request(url, params);
wx.setStorageSync(cacheKey, {
timestamp: Date.now(),
content: freshData
});
return freshData;
}
三、界面开发实践
1. WXML布局
<!-- pages/index/index.wxml -->
<view class="container">
<view class="location">
<image src="/images/location.png"></image>
<text>{{location}}</text>
</view>
<view class="weather-card" wx:if="{{weather}}">
<view class="temp">{{weather.temp}}℃</view>
<view class="meta">
<text>湿度 {{weather.humidity}}%</text>
<text>风速 {{weather.windSpeed}}km/h</text>
</view>
</view>
<button bindtap="refresh">刷新数据</button>
</view>
2. WXSS样式优化
/* pages/index/index.wxss */
.weather-card {
background: linear-gradient(135deg, #89CFF0, #6495ED);
border-radius: 24rpx;
padding: 40rpx;
color: white;
box-shadow: 0 8rpx 16rpx rgba(0,0,0,0.1);
}
.temp {
font-size: 72rpx;
font-weight: bold;
margin-bottom: 20rpx;
}
.meta text {
display: block;
font-size: 28rpx;
opacity: 0.9;
}
四、性能优化方案
图片懒加载:<image lazy-load>
使用<scroll-view>实现虚拟列表
预请求关键数据
启用分包加载
// app.json分包配置
{
"subpackages": [
{
"root": "packageA",
"pages": ["pages/forecast", "pages/alarm"]
}
]
}
五、开发经验总结
1、异常处理:网络错误、API限流、定位失败等场景
2、用户体验:骨架屏加载、错误状态提示
3、安全实践:API密钥加密存储、HTTPS强制要求
4、跨端适配:不同设备尺寸处理方案
未来展望
随着小程序能力的持续开放,未来可结合WebGL实现3D天气效果,利用云开发实现用户偏好存储,通过AI技术实现天气预测与穿衣建议等智能功能。
总结
结构完整:从开发准备到部署优化全流程覆盖
技术深度:包含核心功能代码和优化方案法。