将 SVG 图形封装成一个 Vue 3 组件

28 min read

要将 SVG 图形封装成一个 Vue 3 组件,首先需要创建一个 .vue 文件。在该文件中,可以使用 <template> 标签来定义组件的模板,使用 <script> 标签来定义组件的逻辑,使用 <style> 标签来定义组件的样式。以下是一个简单的示例:

<template>
  <svg :width="width" :height="height">
    <!-- SVG 图形内容 -->
  </svg>
</template>

<script>
export default {
  props: {
    width: {
      type: Number,
      required: true
    },
    height: {
      type: Number,
      required: true
    }
  }
}
</script>

<style scoped>
/* 组件的样式 */
</style>

在上述示例中,组件接受 widthheight 两个 props,用于指定 SVG 图形的宽度和高度。你可以在 <svg> 标签中编写 SVG 图形的具体内容,可以使用标签、路径、图形等 SVG 元素来创建图形。在组件的样式中,你可以使用 CSS 来美化 SVG 图形。

在使用该组件时,可以使用 <svg-component> 标签来引用它,并传入相应的 props 值,例如:

<template>
  <div>
    <svg-component width="100" height="100"></svg-component>
  </div>
</template>

<script>
import SvgComponent from './SvgComponent.vue'

export default {
  components: {
    SvgComponent
  }
}
</script>

在上述示例中,我们将 <svg-component> 标签引入了一个名为 SvgComponent 的组件,并分别传入了 width="100"height="100" 这两个 props。这样,我们就可以在页面中使用封装好的 SVG 图形组件了。