一、资源管理
-
静态资源路径规范
- 项目根目录创建
static文件夹存放资源(图片/字体/JSON等) - 引用方式:
<!-- 模板中 --> <image src="/static/logo.png"></image> <!-- JS中 --> data() { return { icon: require('@/static/home.png') } } <!-- CSS中 --> .bg { background-image: url('~@/static/bg.jpg'); }
- 项目根目录创建
-
资源优化策略
- 图片压缩:使用工具如 TinyPNG 提前压缩
- 按需加载:通过
v-if控制非首屏资源加载 - CDN 加速:大文件通过
<script src="https://cdn.com/lib.js">引入
-
资源加载最佳实践
// 动态加载示例 export default { methods: { loadResource() { uni.downloadFile({ url: 'https://example.com/data.json', success: (res) => { if (res.statusCode === 200) { this.data = JSON.parse(res.data) } } }) } } }
二、样式适配方案
-
单位系统
- 使用
rpx响应式单位(推荐) $$ 1rpx = \frac{\text{屏幕宽度}}{750} $$ - 示例:设计稿 750px 宽 → 直接写
750rpx
- 使用
-
多端适配方案
/* 通用样式 */ .container { padding: 32rpx; /* #ifdef H5 */ background: blue; /* 仅H5生效 */ /* #endif */ } /* 设备尺寸适配 */ @media screen and (max-width: 600px) { .item { flex-direction: column; } } -
全局样式管理
在App.vue中引入全局样式:/* 引入通用变量 */ @import '@/common/uni.css'; /* 定义全局变量 */ :root { --primary-color: #007AFF; --spacing-base: 16rpx; }
三、深度适配技巧
-
安全区域处理
.safe-area { padding-bottom: constant(safe-area-inset-bottom); padding-bottom: env(safe-area-inset-bottom); } -
横竖屏适配
// 监听屏幕旋转 onReady() { uni.onWindowResize((res) => { if (res.size.windowWidth > res.size.windowHeight) { this.isLandscape = true } }) } -
主题切换方案
// 动态切换主题 toggleTheme() { uni.setStorageSync('theme', this.darkMode ? 'dark' : 'light') document.documentElement.setAttribute('data-theme', this.darkMode ? 'dark' : 'light') }
四、性能优化建议
- 避免使用
@import在单文件组件中引入 CSS - 复杂动画使用
transform代替top/left - 使用 CSS 变量代替重复值:
:root { --theme-color: #f00; } .text { color: var(--theme-color); }
实践提示:开发阶段使用
uni.upx2px(750)实时查看 rpx 转换值,发布前运行uni build自动优化资源引用路径。
UniApp样式适配与资源管理技巧
4万+

被折叠的 条评论
为什么被折叠?



