uni-app开发中条件编译

147 阅读1分钟

条件编译

image.png

最简单的方式!!!

uni-app官网条件编译

 // #ifdef MP-WEIXIN
  <view style="display: flex">
    <u-button @click="gotest(1)" text="管理员查询房东列表"> </u-button>
    <u-button @click="gotest(2)" text="警员:默认页"> </u-button>
  </view>
  // #endif

image.png

image.png

加上这两行代码就可以实现条件编译了,如果你想在h5的平台上显示,把MP-WEIXIN改成H5就可以了

需要判断环境变量(麻烦不推荐)

我们在使用uni-app开发小程序和h5页面的时候有时候需要不同的编译方式,所以就需要进行条件编译 我是把条件编译的代码放在了pinia仓库中,需要条件编译的时候直接去仓库取出来进行判断就可以。

  1. 将判断平台的方法写在pinia中
import { defineStore } from 'pinia';
import { ref } from 'vue';

export const useUserStore = defineStore(
  'user',
  () => {
    // 项目中需要存储的变量
    let userId = ref(''); // 用户唯一标识
    // 平台判断
    const isH5 = () => process.env.UNI_PLATFORM === 'h5';
    const isMP = () => process.env.UNI_PLATFORM === 'mp-weixin';

    return {
      // 导出
      userId
      // 直接作为 store 的属性
      isH5,
      isMP,
    };
  },
  {
    persist: {
      enabled: true, // 启用持久化

      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value);
        },
        getItem(key) {
          return uni.getStorageSync(key);
        },
      },
    },
  },
);
  1. 配置完后我们需要调用pinia,并执行isH5,isMP这两个函数即可
<template>
  <div>我的</div>
  <view v-if="store.isH5()">我是h5的页面</view>
  <view v-if="store.isMP()">我是微信小程序的页面</view>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue';
import { useUserStore } from '@/stores/index.js';
import { onShow } from '@dcloudio/uni-app';

const store = useUserStore();
const userId = ref();

// 仅在小程序中使用 onShow
onShow(() => {
  if (store.isMP()) console.log('微信小程序页面');
});

// 在 H5 中使用 onMounted
onMounted(() => {
  if (store.isH5()) getUserId();
  console.log(store.isH5(), store.isMP());
});

// 获取用户登录唯一标识
const getUserId = () => {
  userId.value = store.userId;
  console.log('仓库中的数据', userId.value);
  if (!userId.value) {
    uni.navigateTo({
      url: '/pages/Login/index',
    });
  }
};
</script>

<style lang="scss" scoped></style>

这样我们就可以在不同的平台上使用不同的方法了。