<返回目录     Powered by claud/xia兄

第12课: 条件编译

多平台适配实战

课程内容

本课程将详细介绍UniApp中的条件编译功能,以及如何使用条件编译实现多平台适配。

核心概念

条件编译语法

1. 模板中的条件编译

<!-- #ifdef H5 -->
<view>这段代码只在H5平台显示</view>
<!-- #endif -->

<!-- #ifdef MP-WEIXIN -->
<view>这段代码只在微信小程序平台显示</view>
<!-- #endif -->

<!-- #ifdef APP-PLUS -->
<view>这段代码只在App平台显示</view>
<!-- #endif -->

2. 脚本中的条件编译

// #ifdef H5
console.log('这段代码只在H5平台执行');
// #endif

// #ifdef MP-WEIXIN
console.log('这段代码只在微信小程序平台执行');
// #endif

// #ifdef APP-PLUS
console.log('这段代码只在App平台执行');
// #endif

3. 样式中的条件编译

/* #ifdef H5 */
.h5-only {
    color: red;
}
/* #endif */

/* #ifdef MP-WEIXIN */
.mp-weixin-only {
    color: blue;
}
/* #endif */

/* #ifdef APP-PLUS */
.app-plus-only {
    color: green;
}
/* #endif */

多平台适配实战

1. 平台判断

// 获取当前平台信息
const platform = uni.getSystemInfoSync().platform;
console.log('当前平台:', platform);

// 根据平台执行不同逻辑
if (platform === 'ios') {
    console.log('iOS平台');
} else if (platform === 'android') {
    console.log('Android平台');
} else if (platform === 'devtools') {
    console.log('开发者工具');
} else if (platform === 'h5') {
    console.log('H5平台');
}

2. API调用适配

// 调用平台特定API
// #ifdef APP-PLUS
uni.getAppBaseInfo({
    success: function(res) {
        console.log('App基础信息:', res);
    }
});
// #endif

// #ifdef MP-WEIXIN
wx.getNetworkType({
    success: function(res) {
        console.log('网络类型:', res.networkType);
    }
});
// #endif

3. 组件适配

<template>
    <view>
        <!-- #ifdef H5 -->
        <button @click="handleH5Click">H5按钮</button>
        <!-- #endif -->
        
        <!-- #ifdef MP-WEIXIN -->
        <button open-type="getUserInfo" @getuserinfo="handleWeixinUserInfo">微信登录</button>
        <!-- #endif -->
        
        <!-- #ifdef APP-PLUS -->
        <button @click="handleAppClick">App按钮</button>
        <!-- #endif -->
    </view>
</template>

<script>
export default {
    methods: {
        handleH5Click() {
            console.log('H5按钮点击');
        },
        handleWeixinUserInfo(e) {
            console.log('微信用户信息:', e.detail.userInfo);
        },
        handleAppClick() {
            console.log('App按钮点击');
        }
    }
}
</script>
重要提示:

实践练习

练习任务:
  1. 创建一个包含多平台适配的页面
  2. 在不同平台显示不同的内容
  3. 调用平台特定的API
  4. 测试在不同平台的表现

总结

通过本课的学习,你应该掌握了条件编译的基本语法和多平台适配的最佳实践。在实际项目中,合理使用条件编译可以帮助你更好地适配不同平台的特性和限制。