1. 定义子组件
<template> <!-- svg:图标外层容器节点,内部需要与use标签结合使用 --> <svg :style="{ width, height }"> <!-- xlink:href表示执行用哪一个图标,属性值要为#icon-图标名字 --> <!-- use标签fill属性可以设置图标的颜色 --> <use :xlink:href="prefix + name" :fill="color"></use> </svg> </template> <script setup lang="ts"> // 接受父组件传递过来的参数 defineProps({ // xlink:href属性值前缀 prefix: { type: String, default: "#icon-" }, // 提供使用的图标名字 name: String, // 接受父组件传递的颜色 color: { type: String, default: "" }, // 接受父组件传过来的宽高 width: { type: String, default: "30px" }, height: { type: String, default: "30px" } }); </script> <style scoped></style>
2. 父组件引用
<template> <div> <svg-icon width="40px" height="40px" name="home"></svg-icon> </div> </template> <script setup lang="ts"> // 引入子组件 import SvgIcon from "@/components/SvgIcon/index.vue"; </script> <style scoped></style>
3. 效果