Using Ant Design Vue with Vue 3
Integrating the Ant Design Vue component library into a Vue 3 project is an efficient way to build modern web applications. Ant Design Vue is an open-source UI component library developed based on native Vue 2.x and Vue 3.x. It provides a rich set of beautiful interface elements, including buttons, tables, forms, and layouts, while also supporting dark mode, aligning with modern design trends.
First, ensure that your project has Vue 3 installed. If not, you can create a new project using Vue CLI or Vite. Next, install Ant Design Vue and its dependencies using npm or yarn:
npm install ant-design-vue vue-router
yarn add ant-design-vue vue-router
After installation, you need to import and register the component library in main.js or main.ts. Ant Design Vue offers two registration methods: global registration and on-demand registration. For most projects, on-demand registration is recommended to reduce bundle size.
Configuring Styles and Theme Customization
By default, Ant Design Vue imports a complete set of CSS files. To keep the page clean, we typically only import the necessary styles. In main.js, import the core styles:
import 'ant-design-vue/dist/reset.css'; // Removes the default ant-design.min.css
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import zhCN from 'ant-design-vue/es/locale/zh_CN';
const app = createApp(App);
app.use(router);
app.use(zhCN); // Register Chinese language pack
app.mount('#app');
Using reset.css gives you a clean starting point, avoiding style conflicts. Additionally, Ant Design Vue supports deep customization of theme colors. You can create a theme.less file in the root directory to define custom color variables, then override them in components using the :deep() selector:
@primary-color: #1890ff;
.ant-btn-primary {
background-color: @primary-color !important;
}
Practical Usage of Basic Components
Once installed and configured, you can use components directly in your pages. Below is an example code containing common components:
<template>
<div class="container">
<a-card title="User Information" :bordered="false">
<a-button type="primary" @click="handleLogin">Login</a-button>
<a-alert message="Welcome to Ant Design Vue" show-icon />
<a-table
column-key="name"
:data-source="users"
:columns="columns"
/>
</a-card>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { Button, Alert, Table, message } from 'ant-design-vue';
const users = ref([
{ key: '1', name: 'Zhang San', age: 25 },
{ key: '2', name: 'Li Si', age: 30 },
]);
const columns = [
{ title: 'Name', dataIndex: 'name' },
{ title: 'Age', dataIndex: 'age' },
];
const handleLogin = () => {
message.success('Login successful');
};
</script>
<style scoped>
.container {
padding: 20px;
}
</style>
In this example, we use components such as a-card, a-button, a-alert, and a-table. Through the <script setup> syntax, we can concisely define data and event handling logic.
Forms and Interaction Logic
Ant Design Vue provides powerful support for form processing, including automatic validation, error messages, and more. Below is an example with form validation:
<template>
<a-form :model="form" :rules="rules" layout="vertical">
<a-form-item label="Username">
<a-input v-model:value="form.username" />
</a-form-item>
<a-form-item label="Password">
<a-password-input v-model:value="form.password" show-password-toggle />
</a-form-item>
<a-form-item>
<a-button type="primary" html-type="submit">Submit</a-button>
</a-form-item>
</a-form>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { Form, Input, PasswordInput } from 'ant-design-vue';
const formRef = ref(null);
const form = reactive({
username: '',
password: '',
});
const rules = {
username: [{ required: true, message: 'Please enter your username', trigger: 'blur' }],
password: [
{ required: true, message: 'Please enter your password', trigger: 'blur' },
{ min: 6, message: 'Password must be at least 6 characters long', trigger: 'change' },
],
};
const handleSubmit = async (values) => {
try {
await formRef.value.validate();
console.log('Form validation passed:', values);
} catch (error) {
console.error('Form validation failed:', error);
}
};
</script>
This example demonstrates how to build an interactive form by combining a-form with a-input and a-password-input. Through the :rules attribute, we can define complex validation rules and automatically trigger checks upon submission.
Routing and Page Navigation
In Vue 3 projects, Ant Design Vue is often used in conjunction with Vue Router to implement single-page application (SPA) navigation. Below is a simple routing configuration example:
// router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';
const routes = [
{ path: '/', name: 'Home', component: Home },
{ path: '/about', name: 'About', component: About },
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
In page components, navigation links can be implemented using the <router-link> tag for a polished experience:
<template>
<nav>
<a-link href="/about">About Us</a-link>
<a-link href="https://ant.design" target="_blank" rel="noopener noreferrer">Ant Design</a-link>
</nav>
</template>
In this way, we can upgrade traditional <a> tags to the more feature-rich a-link component while maintaining consistency in the navigation experience.
Summary and Best Practices
Integrating Ant Design Vue into a Vue 3 project not only improves development efficiency but also ensures UI consistency and professionalism. In actual development, it is recommended to follow these best practices:
- Prefer on-demand imports to avoid excessive bundle size;
- Reasonably configure theme colors to match brand requirements;
- Fully utilize form validation features to enhance user experience;
- Combine with Vue Router for smooth page transition experiences;
- Pay attention to state management and data passing between components.
By following the steps above, developers can quickly build web application interfaces that are both beautiful and practical.