UI框架的使用注意事项

590 阅读2分钟

vant

在 vite 项目中按需引入组件(推荐)在 vite 项目中使用 Vant 时,推荐vite-plugin-style-import它可以自动按需引入组件的样式。

1.安装插件

# 通过 npm 安装
npm i vite-plugin-style-import@1.4.1 -D

# 通过 yarn 安装
yarn add vite-plugin-style-import@1.4.1 -D

# 通过 pnpm 安装
pnpm add vite-plugin-style-import@1.4.1 -D

2.配置插件

vite.config.js

import vue from '@vitejs/plugin-vue';
import styleImport, { VantResolve } from 'vite-plugin-style-import';

export default {
  plugins: [
    vue(),
    styleImport({
      resolves: [VantResolve()],
    }),
  ],
};

3.引入组件

import { createApp } from 'vue';
import { Button } from 'vant';

const app = createApp();
app.use(Button);

在非vite项目中使用vant

推荐babel-plugin-import插件,它会在编译过程中将 import 语句自动转换为按需引入的方式。

1.安装插件

npm i babel-plugin-import -D

2.配置插件

在.babelrc 或 babel.config.js 中添加配置:

{
  "plugins": [
    [
      "import",
      {
        "libraryName": "vant",
        "libraryDirectory": "es",
        "style": true
      }
    ]
  ]
}

3.引入组件

接着你可以在代码中直接引入 Vant 组件,插件会自动将代码转化为按需引入的形式。

// 原始代码
import { Button } from 'vant';

// 编译后代码
import Button from 'vant/es/button';
import 'vant/es/button/style';


导入所有组件(不推荐)

import { createApp } from 'vue';
import Vant from 'vant';
import 'vant/lib/index.css';

const app = createApp();
app.use(Vant);

- 组件注册

1.全局注册

import { Button } from 'vant';
import { createApp } from 'vue';

const app = createApp();

// 方式一. 通过 app.use 注册
// 注册完成后,在模板中通过 <van-button> 或 <VanButton> 标签来使用按钮组件
app.use(Button);

// 方式二. 通过 app.component 注册
// 注册完成后,在模板中通过 <van-button> 标签来使用按钮组件
app.component(Button.name, Button);

2.局部注册

import { Button } from 'vant';

export default {
  components: {
    [Button.name]: Button,
  },
};

3.<script setup>(vue3)

<script setup> 中可以直接使用 Vant 组件,不需要进行组件注册。

<script setup>
  import { Button } from 'vant';
</script>

<template>
  <Button />
</template>

4.JSX/TSX(react)

import { Button } from 'vant';

export default {
  render() {
    return <Button />;
  },
};

浏览器适配

1.viewport 布局

Vant 默认使用 px 作为样式单位,如果需要使用 viewport 单位 (vw, vh, vmin, vmax),推荐使用 postcss-px-to-viewport进行转换。postcss-px-to-viewport是一款 PostCSS 插件,用于将 px 单位转化为 vw/vh 单位。

// postcss.config.js
module.exports = {
  plugins: {
    'postcss-px-to-viewport': {
      viewportWidth: 375,
    },
  },
};

2.Rem 布局适配

如果需要使用 rem 单位进行适配,推荐使用以下两个工具:

// postcss.config.js
module.exports = {
  plugins: {
    'postcss-pxtorem': {
      rootValue: 37.5,
      propList: ['*'],
    },
  },
};