封装Vue3组件的全过程

lxf2023-11-26 17:30:01

这是我参与8月更文挑战的第7天,活动详情查看:8月更文挑战

前端开发中使用组件可以大幅度提升整个项目的开发效率,而且使项目更容易维护。 这里楼主以封装一个 Loader 组件为例,记录其封装过程。

需求分析

1、全局 Loader 组件
2、实现自定义显示文案及背景颜色(主要考虑到不需要背景的场景)
3、实现 loading 动画

基础编码

准备工作:新建 Loader.vue 文件

// Loader.vue
<template>
  <div class="loader" :style="{background: background}">
      <div>
        <div class="icon-loading"></div>
        <label class="text-loading">{{ text }}</label>
      </div>
    </div>
</template>

<script lang="ts">
import { defineComponent, onUnmounted } from 'vue'
export default defineComponent({
  props: {
    text: {
      type: String,
      default: '加载中...'
    },
    background: {
      type: String
    }
  }
})
</script>

<style>
  // todo
</style>

可以看出组件接收两个参数:
(1)text: 提升文案。默认为“加载中...”
(2)background:背景颜色。

下面继续完成样式部分

<style>
.loader{
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0,0,0,.2);
}
.loader>div{
  width: 130px;
  height: 130px;
  border-radius: 15px;
  background-color: rgba(0,0,0,.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.loader .text-loading{
  color: #fff;
}
</style>
组件使用及效果

template部分

<Loader v-if="!loading"></Loader>

ts部分

import { useStore } from 'vuex'
import Loader from './components/Loader.vue'

setup () {
    const store = useStore();
    const loading = computed(() => store.state.loading);
    return {
      loading
    }
  }

基础效果:
封装Vue3组件的全过程

继续添加 loading 动画
loading 动画实现的方式多种多样,可以用gif图片,可以用SVG,可以用字体。楼主这里就用CSS3实现一个简单的loading动画

<template>
  ...
  <div>
    <div class="icon-loading"></div>
    <label class="text-loading">{{ text }}</label>
  </div>
</template>

<style>
.loader .icon-loading{
  width: 30px;
  height: 30px;
  border-radius: 30px;
  margin-bottom: 12px;
  border: 6px solid #518cff;
  border-bottom-color: #f1f1f1;
  animation: loading .8s linear infinite;
}
@keyframes loading {
  to {
    transform: rotate(0deg);
  }
  from {
    transform: rotate(-360deg);
  }
}
</style>

最终效果: 封装Vue3组件的全过程

优化组件

此时已经完成了一个 Loader 组件的封装,我们可以进一步优化。Loader 是一个全局样式的组件,但是现在是被包裹在我们页面内容里面的。所以我们使用 vue3 的传送门技术来优化一下结构。

(1)使用 teleport 标签将组件包裹起来

<template>
  <teleport to="#back">
    ...
  </teleport>
</template>

(2)组件挂载之前在 body 节点新增节点,并在组件卸载时移除节点

import { onUnmounted } from 'vue'

setup () {
    const node = document.createElement('div');
    node.id = 'back';
    document.body.appendChild(node);
    onUnmounted(() => {
      document.body.removeChild(node);
    })
  }

完!

本网站是一个以CSS、JavaScript、Vue、HTML为核心的前端开发技术网站。我们致力于为广大前端开发者提供专业、全面、实用的前端开发知识和技术支持。 在本网站中,您可以学习到最新的前端开发技术,了解前端开发的最新趋势和最佳实践。我们提供丰富的教程和案例,让您可以快速掌握前端开发的核心技术和流程。 本网站还提供一系列实用的工具和插件,帮助您更加高效地进行前端开发工作。我们提供的工具和插件都经过精心设计和优化,可以帮助您节省时间和精力,提升开发效率。 除此之外,本网站还拥有一个活跃的社区,您可以在社区中与其他前端开发者交流技术、分享经验、解决问题。我们相信,社区的力量可以帮助您更好地成长和进步。 在本网站中,您可以找到您需要的一切前端开发资源,让您成为一名更加优秀的前端开发者。欢迎您加入我们的大家庭,一起探索前端开发的无限可能!