主要是利用特定的注释语法
1. 条件编译
原理:uni-app 支持条件编译,通过特定的注释语法,可以在不同的平台下编译不同的代码,从而实现页面内容的差异化。
<template>
<view>
<!-- #ifdef H5 -->
<view>这是 H5 页面特有的内容</view>
<!-- #endif -->
<!-- #ifdef MP-WEIXIN -->
<view>这是微信小程序特有的内容</view>
<!-- #endif -->
<view>这是所有平台通用的内容</view>
</view>
</template>
<script>
export default {
data() {
return {
// 通用数据
};
},
onLoad() {
// #ifdef H5
console.log('这是 H5 平台的逻辑');
// #endif
// #ifdef MP-WEIXIN
console.log('这是微信小程序平台的逻辑');
// #endif
}
};
</script>
<style>
/* 通用样式 */
/* #ifdef H5 */
/* H5 特有的样式 */
/* #endif */
/* #ifdef MP-WEIXIN */
/* 微信小程序特有的样式 */
/* #endif */
</style>
2. 动态加载组件
原理:根据不同的平台动态加载不同的组件,将差异部分封装在不同的组件中,在运行时根据平台选择加载。
创建两个不同的组件分别用于 H5(H5Component.vue
)和微信小程(WechatComponent.vue
)
然后在页面中根据平台动态加载组件:
<template>
<view>
<component :is="currentComponent"></component>
<view>这是通用内容</view>
</view>
</template>
<script>
import H5Component from './H5Component.vue';
import WechatComponent from './WechatComponent.vue';
export default {
data() {
return {
currentComponent: ''
};
},
onLoad() {
// #ifdef H5
this.currentComponent = H5Component;
// #endif
// #ifdef MP-WEIXIN
this.currentComponent = WechatComponent;
// #endif
}
};
</script>
3. 路由配置差异化
原理:根据不同的平台配置不同的路由,将差异页面分别配置到不同的路由中,在不同平台下访问不同的页面。
在 pages.json
中进行如下配置:
{
"pages": [
{
"path": "pages/commonPage",
"style": {
"navigationBarTitleText": "通用页面"
}
},
// #ifdef H5
{
"path": "pages/h5Page",
"style": {
"navigationBarTitleText": "H5 专属页面"
}
},
// #endif
// #ifdef MP-WEIXIN
{
"path": "pages/wechatPage",
"style": {
"navigationBarTitleText": "微信小程序专属页面"
}
},
// #endif
],
"globalStyle": {
"navigationBarBackgroundColor": "#FFFFFF",
"navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app 项目",
"backgroundColor": "#F8F8F8",
"backgroundTextStyle": "dark"
}
}
利用路由配置差异化 ,在页面跳转的时候可以这样做:
<template>
<view>
<button @click="goToCommonPage">前往通用页面</button>
<!-- #ifdef H5 -->
<button @click="goToH5Page">前往 H5 专属页面</button>
<!-- #endif -->
<!-- #ifdef MP-WEIXIN -->
<button @click="goToWechatPage">前往微信小程序专属页面</button>
<!-- #endif -->
</view>
</template>
<script>
export default {
methods: {
goToCommonPage() {
uni.navigateTo({
url: '/pages/commonPage/commonPage'
});
},
goToH5Page() {
uni.navigateTo({
url: '/pages/h5Page/h5Page'
});
},
goToWechatPage() {
uni.navigateTo({
url: '/pages/wechatPage/wechatPage'
});
}
}
};
</script>
4. 环境变量判断
原理:在代码中获取当前的运行环境,根据环境变量来决定页面的展示内容或执行不同的逻辑。
<template>
<view>
<view v-if="isH5">这是 H5 页面显示的内容</view>
<view v-if="isWechat">这是微信小程序页面显示的内容</view>
<view>这是通用内容</view>
</view>
</template>
<script>
export default {
data() {
return {
isH5: false,
isWechat: false
};
},
onLoad() {
const platform = uni.getSystemInfoSync().platform;
this.isH5 = platform === 'web';
this.isWechat = platform === 'mp-weixin';
}
};
</script>