创建属于自己的 Vue 3 组件库:主题切换与样式管理
构建一个主题化的 Vue 3 组件库需要多个步骤,包括项目的初始化、组件的创建、主题的实现和样式的管理。以下是详细的步骤和实现代码。
1. 初始化项目
使用 Vite 创建 Vue 3 项目:
npm create vite@latest my-vue3-component-library --template vue
cd my-vue3-component-library
npm install
如果执行 npm run dev 报错,可以检查 node 版本,保证版本 16+
2. 安装依赖
你可能需要安装一些额外的依赖,如 vue
和 vue-router
(如果你打算添加路由支持):
npm install vue@next
如果你还需要支持样式的预处理器(如 SCSS),可以安装 Sass:
下面代码已使用Sass,需要执行:
npm install -D sass
3. 项目结构
my-vue3-component-library/
├── node_modules/
├── public/
├── src/
│ ├── components/
│ │ ├── Button.vue
│ │ ├── Card.vue
│ │ └── ThemeSwitcher.vue
│ ├── styles/
│ │ ├── dark-theme.scss
│ │ └── theme.scss
│ ├── App.vue
│ ├── main.js
├── index.html
├── package.json
├── vite.config.js
└── ...
4. 创建基础组件
1.Button.vue
<template>
<button :class="`btn btn-${type}`" :disabled="isDisabled">
<slot></slot>
</button>
</template>
<script>
export default {
name: 'Button',
props: {
type: {
type: String,
default: 'primary',
},
isDisabled: {
type: Boolean,
default: false,
},
},
};
</script>
<style scoped>
.btn {