uniapp多终端适配
uniapp多终端适配方法
1. 条件编译实现平台差异化代码
通过#ifdef、#endif等条件编译指令处理不同平台的逻辑差异。例如微信小程序和H5的API调用方式不同:
// #ifdef H5
window.location.href = 'https://example.com';
// #endif
// #ifdef MP-WEIXIN
wx.navigateTo({ url: '/pages/index' });
// #endif
2. 响应式布局与Flex布局
使用flex布局配合rpx单位自动适配不同屏幕尺寸。750rpx等于屏幕宽度,元素尺寸使用rpx可等比缩放:
.container {
display: flex;
width: 750rpx;
}
.item {
flex: 1;
height: 200rpx;
}
3. 动态样式处理
通过uni.getSystemInfoSync()获取设备信息动态调整样式:
const systemInfo = uni.getSystemInfoSync();
const isSmallScreen = systemInfo.screenWidth < 375;
this.setData({ fontSize: isSmallScreen ? '14px' : '16px' });
4. 多端组件适配 创建平台专属组件目录结构:
/components/
├─ comp-name/
│ ├─ comp-name.vue # 通用组件
│ ├─ comp-name-h5.vue # H5专用
│ └─ comp-name-mp.vue # 小程序专用
5. API统一封装 对平台特有API进行二次封装,例如统一导航方法:
export function navigateTo(url) {
// #ifdef H5
window.location.href = url;
// #endif
// #ifdef MP-WEIXIN
wx.navigateTo({ url });
// #endif
}
6. 自动化测试工具
使用uni-app官方提供的自动化测试方案,通过uni-test-utils在不同平台运行测试用例:
import { mount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'
test('multi-platform test', () => {
const wrapper = mount(MyComponent)
expect(wrapper.html()).toContain('Hello')
})
7. 构建配置优化
在manifest.json中配置不同平台的构建参数:
{
"h5": {
"router": { "mode": "history" }
},
"mp-weixin": {
"appid": "YOUR_APPID"
}
}
8. 图片资源适配
使用@2x和@3x命名规范存放多倍图,系统会自动选择合适尺寸:
/static/
├─ logo@2x.png
└─ logo@3x.png
9. 字体适配方案
通过CSS的@font-face配合媒体查询实现:
@font-face {
font-family: 'CustomFont';
src: url('/static/font-small.woff') format('woff');
}
@media (min-width: 768px) {
@font-face {
font-family: 'CustomFont';
src: url('/static/font-large.woff') format('woff');
}
}
10. 性能优化策略 针对不同平台采用特定的优化手段:
- H5端使用懒加载和预加载
- 小程序端启用分包加载
- App端使用原生插件加速渲染
通过以上方法组合使用,可有效实现uniapp应用在iOS、Android、H5、微信小程序、支付宝小程序等多终端的适配需求。实际开发中建议建立适配检查清单,在每次发版前验证各平台表现。







