Cross-terminal practice | How to use the Vant component library in the Taro framework - adapting to multiple terminals

Using Vant, the open source mobile component library of the Youzan front-end team, in Taro, about 70% of the components that can be directly used are compatible, but it cannot be 100% compatible.

So how do we adjust to achieve multi-terminal adaptation of all components? After much exploration and practice, the team finally found a bright road.

Cross-end UI library selection

Taro is a multi-end development solution created by JD.com Labs. When using the Taro framework for business development, the core purpose is to be able to write only one set of code to achieve consistent performance on different sides. From the project side, in layman's terms, it is to make the product go online quickly. Then when using the Taro framework, we also need to choose a high-quality cross-end component library to improve the efficiency of developers to draw pages.

At present, the popular mobile terminal component libraries mainly include Mint UI, WeUI, iView UI, layui, ElementUI, vant UI, and so Antd Design Mobileon. In the past, when developing an H5 project, the designer selected a UI component library with a suitable style, and then developed and used it directly. But when we use Taro's cross-end solution, we can't choose these UI libraries at will, because these UI libraries may not have achieved the corresponding cross-end compatibility. However, there is no need to worry too much. The Taro team has long considered this problem, and has provided some access solutions for some commonly used UI component libraries. Of course, the official main push is the official UI library: Taro UI, NutUI, but sometimes we just do it 偏偏不用官方推荐的.

From the official blog log , we found that there are three UI libraries that can be used WeUI, vant UI, , and the official have done the corresponding module encapsulation. Antd Design MobileConsidering that the team used the vue syntax stack in the later stage, and analyzed the overall situation of the current three Demo cases, it was finally believed that it Vant UImay be more suitable for the later business scenarios.

Compatibility of Vant UI in Taro

As mentioned above, using Vant, the open source mobile component library of the Youzan front-end team, in Taro, the components that can be directly used are about 70%, but cannot be 100% compatible. There is no other reason, because Vant is a mobile component library developed for the web, and in the applet, due to the call limitations of some unique APIs (for example: API for obtaining element size series, etc.), all functions cannot be synchronized and compatible. (However, the method is always more difficult than the difficulty.)

For the current component support, please refer to: taro-vant component support list

How to use the Vant component library reasonably in Taro

Vant is a mobile component library open sourced by the Youzan front-end team. It was open sourced in 2017. Currently, Vant vue version (vant) and WeChat applet version (vant-weapp) are officially provided, which means that for different scenarios, different component libraries should be selected according to local conditions.

Vant Weapp alone

The Vant Weapp component library is an open source mobile component library that supports WeChat mini-programs open sourced by the Youzan front-end team. If in the business scenario, the Taro framework is only used to develop WeChat mini-programs, it is more suitable to use Vant Weapp directly than Vant.

Note: Projects developed using Vant Weapp's native third-party component library no longer have the ability to convert multiple terminals.

[Step 1]: Configure the style and size conversion that ignores vant. If you use the Vant weapp component directly, you will find that the style is too small. This is because Taro converts the style size of Vant weapp from px to rpx by default. You can disable the conversion through configuration. Choose one of the following two methods:

Method 1: Configure selectorBlackList

// config/index.js

const config = {
  // ...
  mini: {
    postcss: {
      pxtransform: {
        enable: true,
        config: {
          // 过滤 vant 组件库的前缀:van-
          selectorBlackList: [/van-/],
        },
      },
    },
  },
};
复制代码

Method 2: Configure the @tarojs/plugin-html plugin (for compatibility with html tags of web components)

// config/index.js
const config = {
  // ...
  plugins: [
    [
      "@tarojs/plugin-html",
      {
        // 过滤 vant 组件库的前缀:van-
        pxtransformBlackList: [/van-/],
      },
    ],
  ],
};
复制代码

【第二步】:通过配置,将 Vant weapp 原生小程序文件拷贝到编译后的 dist 目录下,特别注意:因为不会检索组件相互调用关系,所以需要主动将wxscommon,以及部分组件调用的组件也一并拷贝,例如:

const config = {
  // ...
  copy: {
    patterns: [
      {
        from: "src/components/vant-weapp/dist/wxs", // 公共模块
        to: "dist/components/vant-weapp/dist/wxs",
      },
      {
        from: "src/components/vant-weapp/dist/common/", // 公共模块
        to: "dist/components/vant-weapp/dist/common/",
      },
      {
        from: "src/components/vant-weapp/dist/button", // 当前将要使用的组件
        to: "dist/components/vant-weapp/dist/button",
      },
      {
        from: "src/components/vant-weapp/dist/loading", // button 组件调用的组件
        to: "dist/components/vant-weapp/dist/loading",
      },
      // ...
    ],
    options: {},
  },
};
复制代码

【第三步】:引用 Vant Weapp 组件,在 app 或者页面 config 配置文件中配置 usingComponents 字段,例如:

export default {
  navigationBarTitleText: "按钮显示页",
  usingComponents: {
    "van-button": "../../components/vant-weapp/dist/button/index",
  },
};
复制代码

【第四步】:在页面中便可以直接使用 button 组件了。特别注意:在 Taro 3.x 版本中发现样式不生效时,需要将属性默认值改为传参形式,原因参考:8955,例如:将<van-button plain>朴素按钮</van-button> 改为 <van-button plain="plain">朴素按钮</van-button>

<template>
  <view>
    <van-button type="primary" :loading="true" loading-text="ing"
      >Button</van-button
    >
    <van-button plain="plain" type="info">朴素按钮</van-button>
  </view>
</template>

<script>
export default {
  name: "index",
};
</script>
复制代码

小程序效果示例如下图:

Vant 单独使用

在 Taro 项目中使用 vant 组件库,与使用其他 npm 包并无多大差别。我们主要还是应该关注 vant 组件在各端上的兼容性差异,然后通过部分调整进行适配。

安装依赖

yarn add vant -S # 或 npm install vant -S
复制代码

在页面中直接使用

<template>
  <view>
    <van-button type="primary">primary</van-button>
  </view>
</template>

<script>
import { Button } from "vant"; // 引入 button 组件

export default {
  components: {
    "van-button": Button,
  },
};
</script>
复制代码

H5 和小程序效果示例如下图:

Vant 和 Vant Weapp 结合使用

在 Taro 中使用 Vant 时,如果存在只有 H5 端适配,而小程序端不适配的情况时。那么我们应该引入 Vant Weapp 库,然后去单独适配微信小程序端。主要方式就是通过 Taro 内置的编译环境变量 process.env.TARO_ENV 来分别加载两个不同端的组件。具体操作如下:

首先,需要将 Vant Weapp 的原生组件引入到当前应用中

// app.config.js  vant weapp 的原生组件可定义在全局配置
export default {
  usingComponents: {
    "van-tab-weapp": "./components/vant-weapp/dist/tab/index",
    "van-tabs-weapp": "./components/vant-weapp/dist/tabs/index",
  },
};
复制代码

然后,将编译时环境变量 process.env.TARO_ENV 赋值到逻辑变量中

import { Tab, Tabs } from "vant"; // h5 端组件
import "./index.less";
export default {
  name: "Index",
  components: {
    "van-tab": Tab,
    "van-tabs": Tabs,
  },
  data() {
    return {
      isH5: process.env.TARO_ENV === "h5",
      isWeapp: process.env.TARO_ENV === "weapp",
    };
  },
};
复制代码

最后,我们可以在页面中添加判断条件,h5 加载 Vant 组件,小程序则加载 Vant Weapp 组件

<template>
  <view>
    <van-tabs v-if="isH5">
      <van-tab title="标签 1">内容 1</van-tab>
    </van-tabs>
    <van-tabs-weapp v-if="isWeapp">
      <van-tab-weapp title="标签 1">内容 1</van-tab-weapp>
    </van-tabs-weapp>
  </view>
</template>
复制代码

H5 和小程序效果示例如下图:

自定义跨端组件

Although Vant, an excellent open source component library project in the community, has been able to meet most business scenarios, there are bound to be some component functions that cannot meet the needs in actual scenarios. For this part of the uncovered functions, in actual development, we need to solve it through a custom compatibility solution. In fact, the developer writes a cross-end component by himself.

Through the built-in environment variables provided by the Taro framework process.env.TARO_ENV, we can write different business codes for different sides, and can also handle the different performances of different sides in a compatible manner.

For example, a label component needs to be developed. If there are differences in the performance of the two ends, then we need to develop an H5 component and a small program component respectively, and then judge whether it is an H5 or a small program environment through the compile-time environment variables to load different end platforms respectively. s component. It is also worth mentioning that for logical js, Taro will call the js file with the corresponding terminal type suffix first according to the current compilation environment. For example, when compiling a WeChat applet, it will first query whether the xxx.weapp.js file exists. When compiling h5, it will first check whether the xxx.h5.js file exists, if not, call xxx.js. Then we can use these features when we write custom cross-end components. Here is a small chestnut.

Custom compatible, the file directory structure can be as follows:

.
├── components
│   ├── customLabel-h5.vue # 单独 h5 组件
│   └── customLabel-weapp.vue # 单独微信小程序组件
├── index.config.js
├── index.less
├── index.vue
├── utils.h5.js # h5优先调用 utils.h5.js
└── utils.weapp.js # 微信小程序优先调用 utils.weapp.js
复制代码

Specific code examples are as follows:

<template>
  <view>
    <custom-label>自定义标签内容</custom-label>
    <view>正文内容</view>
  </view>
</template>
复制代码
let customLabel;
// 在编译阶段,会移除不属于当前编译类型的代码,只保留当前编译类型下的代码
if (process.env.TARO_ENV === "h5") {
  customLabel = require("./components/customLabel-h5.vue").default;
} else {
  customLabel = require("./components/customLabel-weapp.vue").default;
}
import { customFn } from "./utils"; // 会根据编译时环境,找对应的环境后缀文件。若都不存在则找默认`.js`文件
export default {
  name: "Index",
  components: {
    customLabel,
  },
};
复制代码

An example of H5 and applet effects is as follows:

Demo example

References

Guess you like

Origin juejin.im/post/7080176600704090143