Component libraries are an essential part of modern web development. They allow you to create reusable UI components that can be shared across projects and teams. In this article, we'll explore how to build a component library with Vue.js 3.
Setting Up the Project
First, let's create a new Vue.js project using the Vue CLI:
vue create my-component-libraryDuring the setup process, select the features you need for your component library. At a minimum, you'll want to include Babel and Vuex.
Creating Your First Component
Now that we have our project set up, let's create our first component. Create a new file in the src/components directory called Button.vue:
<template>
<button :class="buttonClass" @click="$emit('click')">
<slot></slot>
</button>
</template>
<script>
export default {
name: 'Button',
props: {
variant: {
type: String,
default: 'primary',
validator: value => [
'primary',
'secondary',
'success',
'danger',
'warning',
'info',
'light',
'dark'
].includes(value)
},
size: {
type: String,
default: 'medium',
validator: value => ['small', 'medium', 'large'].includes(value)
}
},
computed: {
buttonClass() {
return [
'btn',
`btn-${this.variant}`,
`btn-${this.size}`
];
}
}
}
</script>
<style scoped>
.btn {
border: none;
border-radius: 4px;
cursor: pointer;
font-weight: 500;
transition: all 0.2s ease;
}
.btn-primary {
background-color: #3490dc;
color: white;
}
.btn-secondary {
background-color: #6c757d;
color: white;
}
.btn-success {
background-color: #38c172;
color: white;
}
.btn-danger {
background-color: #e3342f;
color: white;
}
.btn-warning {
background-color: #f6993f;
color: white;
}
.btn-info {
background-color: #4dc0b5;
color: white;
}
.btn-light {
background-color: #f8f9fa;
color: #212529;
}
.btn-dark {
background-color: #343a40;
color: white;
}
.btn-small {
padding: 0.25rem 0.5rem;
font-size: 0.875rem;
}
.btn-medium {
padding: 0.5rem 1rem;
font-size: 1rem;
}
.btn-large {
padding: 0.75rem 1.5rem;
font-size: 1.25rem;
}
</style>Documenting Your Components
Documentation is crucial for a component library. Vue Styleguidist is a great tool for creating documentation for your Vue.js components. To install it:
npm install --save-dev vue-styleguidistThen, create a configuration file called styleguide.config.js in the root of your project:
module.exports = {
components: 'src/components/**/*.vue',
defaultExample: `
<template>
<div>Your component goes here</div>
</template>
`
}Conclusion
Building a component library with Vue.js is a great way to create reusable UI components that can be shared across projects. By following the steps outlined in this article, you'll be well on your way to creating your own component library.