作者:admin,发布日期:2021-06-02
阅读:1932;评论:0

需要用到vite-plugin-style-import这个插件

插件文档:https://github.com/anncwb/vite-plugin-style-import/blob/HEAD/README.zh_CN.md

创建项目

首先参考之前的文档创建一个vite项目

https://blog.craftyun.cn/post/226.html

然后开始安装ant-design-vue@next,也就是支持vue3的antd

yarn add ant-design-vue@next

至此,项目创建完成

配置按需加载

首先安装vite-plugin-style-import插件,用于支持按需加载。

yarn add vite-plugin-style-import -D
yarn add less -D

然后修改根目录下的vite.config.js,添加插件配置。

添加的内容

    styleImport({
      libs: [
        {
          libraryName: "ant-design-vue",
          esModule: true,
          resolveStyle: (name) => {
            return `ant-design-vue/es/${name}/style/index`;
          },
        },
      ],
    }),
  css: {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
      },
    },
  },

最终的文件

import { defineConfig } from "vite";
import styleImport from "vite-plugin-style-import";
import vue from "@vitejs/plugin-vue";

// https://vitejs.dev/config/
export default defineConfig({
  css: {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
      },
    },
  },
  plugins: [
    vue(),
    styleImport({
      libs: [
        {
          libraryName: "ant-design-vue",
          esModule: true,
          resolveStyle: (name) => {
            return `ant-design-vue/es/${name}/style/index`;
          },
        },
      ],
    }),
  ],
});

配置完成后,创建一个工具类,导入antd需要的组件

在./src/plugins/antd.js中添加以下内容

import { Button, Divider, Input } from "ant-design-vue";

export default {
  install: (app, options) => {
    app.use(Input);
    app.use(Divider);
    app.use(Button);
  },
};

在这个文件里,我们定义了一个vue的插件,然后就可以在main.js里面调用app.use来使用antd.js

修改createApp()为以下内容

createApp(App).use(antd).mount("#app");

修改后的文件:

import { createApp } from "vue";
import App from "./App.vue";
import antd from "./plugins/antd.js";

createApp(App).use(antd).mount("#app");

配置完后测试

修改App.vue,修改为以下内容:

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <a-button @click="testClick">测试</a-button>
  <a-divider />
  用户名:
  <a-input style="width: 200px" v-model="username" />
  <p>{{ username }}</p>
</template>

<script>
import { defineComponent, ref } from "@vue/runtime-core";

export default defineComponent({
  setup() {
    const username = ref("");

    const testClick = () => {
      console.log("test message");
    };

    return {
      username,
      testClick,
    };
  },
});
</script>

<style></style>

最终效果

Snipaste_2021-06-02_17-05-59.jpg

你可能感兴趣的文章

评论区

发表评论

必填

选填

选填

必填

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。