返回

从0到1打造Vue3+TS组件库

前端





## 前言

组件库对于构建大型、可维护的前端应用程序非常重要。它们可以帮助您提高开发效率,确保代码的一致性,并使应用程序更易于维护。

本文将指导您使用Vue3TypeScript从头开始创建组件库。我们将使用Vite作为构建工具,并使用vue-routersass来构建官网。

## 搭建项目

### 1. 初始化项目

首先,我们需要创建一个新的Vue3项目。我们可以使用create-vite-app工具来做到这一点。

npx create-vite-app my-component-library


这将创建一个新的Vue3项目,并安装必要的依赖项。

### 2. 安装vue-router和sass

接下来,我们需要安装vue-router和sass。

npm install vue-router sass


### 3. 搭建官网

现在,我们可以开始搭建官网了。首先,我们需要在`src`目录中创建一个`App.vue`文件。

```html
<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    component: () => import('./Home.vue')
  },
  {
    path: '/components',
    component: () => import('./Components.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default {
  router
}
</script>

<style lang="scss">
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
</style>

接下来,我们需要在src目录中创建一个Home.vue文件。

<template>
  <div>
    <h1>Home</h1>
    <p>Welcome to the home page of my component library.</p>
  </div>
</template>

<script>
export default {

}
</script>

最后,我们需要在src目录中创建一个Components.vue文件。

<template>
  <div>
    <h1>Components</h1>
    <ul>
      <li>Button</li>
      <li>Input</li>
      <li>Dropdown</li>
    </ul>
  </div>
</template>

<script>
export default {

}
</script>

现在,我们可以运行以下命令来启动开发服务器:

npm run dev

这将在浏览器中打开官网。

开发组件

现在,我们可以开始开发组件了。首先,我们需要在src/components目录中创建一个新的文件夹。

mkdir src/components

接下来,我们需要在该文件夹中创建一个新的组件。

touch src/components/Button.vue

在该文件中,我们可以添加以下代码:

<template>
  <button @click="handleClick">
    {{ text }}
  </button>
</template>

<script>
export default {
  props: {
    text: {
      type: String,
      default: 'Button'
    }
  },
  methods: {
    handleClick() {
      this.$emit('click')
    }
  }
}
</script>

<style lang="scss">
button {
  padding: 10px 20px;
  border-radius: 5px;
  background-color: #2c3e50;
  color: #ffffff;
  font-size: 16px;
  cursor: pointer;
}

button:hover {
  background-color: #34495e;
}
</style>

现在,我们可以使用以下代码在其他组件中使用该组件:

<template>
  <div>
    <Button @click="handleClick" />
  </div>
</template>

<script>
import Button from './components/Button.vue'

export default {
  components: {
    Button
  },
  methods: {
    handleClick() {
      console.log('Button clicked!')
    }
  }
}
</script>

结语

本教程向您展示了如何使用Vue3和TypeScript从头开始创建一个组件库。您还学习了如何使用Vite搭建官网,并开发组件。

我希望本教程对您有所帮助。如果您有任何问题,请随时在评论区留言。