08-多端适配与条件编译

4 阅读1分钟

🔀 Taro+Vue3 入门(八):多端适配与条件编译

系列导读:Taro 的精髓在于一套代码多端运行,但各平台总有差异。 Vue3 模板中同样支持条件编译,本文教你优雅处理多端差异。


🔧 1. 条件编译

文件维度

src/components/ShareButton/
  ├── index.vue            # 默认实现
  ├── index.weapp.vue      # 微信专用
  ├── index.h5.vue         # H5 专用
  └── index.alipay.vue     # 支付宝专用

编译时自动选择对应平台的文件。

代码块维度

<script setup lang="ts">
import Taro from '@tarojs/taro'

async function handleLogin() {
  if (process.env.TARO_ENV === 'weapp') {
    const { code } = await Taro.login()
    await authApi.loginByWechat(code)
  } else if (process.env.TARO_ENV === 'h5') {
    Taro.navigateTo({ url: '/pages/login/index' })
  }
}
</script>

模板中条件编译

<template>
  <!-- 注释条件编译 -->
  <!-- #ifdef weapp -->
  <button open-type="share">分享给好友</button>
  <!-- #endif -->

  <!-- #ifdef h5 -->
  <button @tap="copyLink">复制链接</button>
  <!-- #endif -->

  <!-- #ifndef h5 -->
  <button @tap="scanCode">扫一扫</button>
  <!-- #endif -->
</template>

<style lang="scss">
/* #ifdef weapp */
.page { background: #f5f5f5; }
/* #endif */

/* #ifdef h5 */
.page { background: #fff; max-width: 750px; margin: 0 auto; }
/* #endif */
</style>

🧩 2. 平台工具

// src/utils/platform.ts
export const isWeapp = process.env.TARO_ENV === 'weapp'
export const isH5 = process.env.TARO_ENV === 'h5'
export const isAlipay = process.env.TARO_ENV === 'alipay'

export function getSafeAreaBottom(): number {
  const info = Taro.getSystemInfoSync()
  return info.safeArea ? info.screenHeight - info.safeArea.bottom : 0
}
<!-- 使用 -->
<script setup lang="ts">
import { isWeapp, isH5 } from '@/utils/platform'
</script>

<template>
  <button v-if="isWeapp" open-type="share">分享</button>
  <button v-else-if="isH5" @tap="shareViaLink">分享链接</button>
</template>

📱 3. 多端配置

// config/index.ts
const config = {
  h5: {
    publicPath: '/',
    router: { mode: 'browser' },
    devServer: { port: 3000 },
  },
  mini: {
    postcss: {
      pxtransform: { enable: true, config: { designWidth: 750 } },
    },
  },
}

✅ 本篇小结 Checklist

  • 掌握文件维度条件编译(.weapp.vue
  • 掌握模板/样式中注释条件编译
  • 会封装平台判断工具

本文是「Taro+Vue3 入门」系列第 8 篇,共 10 篇。