12、条件注释实现跨端兼容

跨端兼容

uni-app 已将常用的组件、JS API 封装到框架中,开发者按照 uni-app 规范开发即可保证多平台兼容,大部分业务均可直接满足。

但每个平台有自己的一些特性,因此会存在一些无法跨平台的情况。

条件编译

条件编译是用特殊的注释作为标记,在编译时根据这些特殊的注释,将注释里面的代码编译到不同平台。

写法:以 #ifdef 或 #ifndef 加 %PLATFORM% 开头,以 #endif 结尾。

#ifdef:if defined 仅在某平台存在
#ifndef:if not defined 除了某平台均存在
%PLATFORM%:平台名称

更多去官网看:官网->教程->编译器(条件编译)->条件编译处理多端差异

页面上的元素:

比如页面上的元素:

<template>
	<view>
		
		<!-- #ifdef H5 -->
		<view>我希望只在H5页面里显示</view>
		<!-- #endif -->
		
		<!-- #ifdef MP-WEIXIN -->
		<view>我希望只在微信小程序显示</view>
		<!-- #endif -->
		
	</view>
</template>

h5页面:
image

微信小程序里:
image

js代码实现条件注释

	// #ifdef H5
				console.log('我希望只在H5页面打印');
				// #endif
				
				// #ifdef MP-WEIXIN
				console.log('我希望只在小程序页面打印');
				// #endif

css实现条件注释

	/* #ifdef H5 */
	view{
		color:red;
	}
	/* #endif */
	
	/* #ifdef MP-WEIXIN */
	view{
		color:blue;
	}
	/* #endif */

演示实例使用的代码

<template>
	<view>
		
		<!-- #ifdef H5 -->
		<view>我希望只在H5页面里显示</view>
		<!-- #endif -->
		
		<!-- #ifdef MP-WEIXIN -->
		<view>我希望只在微信小程序显示</view>
		<!-- #endif -->
		
	</view>
</template>

<script>
	export default{
		data(){
			return{}
		},
		methods:{			
			onLoad() {
				// #ifdef H5
				console.log('我希望只在H5页面打印');
				// #endif
				
				// #ifdef MP-WEIXIN
				console.log('我希望只在小程序页面打印');
				// #endif
			}
			
		}
		
		
		
	}
</script>

<style>
	/* #ifdef H5 */
	view{
		color:red;
	}
	/* #endif */
	
	/* #ifdef MP-WEIXIN */
	view{
		color:blue;
	}
	/* #endif */
</style>
posted @   青仙  阅读(59)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示