• vue3后台管理框架之svg封装为全局组件


    因为项目很多模块需要使用图标,因此把它封装为全局组件!!!

    在开发项目的时候经常会用到svg矢量图,而且我们使用SVG以后,页面上加载的不再是图片资源,

    这对页面性能来说是个很大的提升,而且我们SVG文件比img要小的很多,放在项目中几乎不占用资源。

    安装SVG依赖插件

    pnpm install vite-plugin-svg-icons -D

    vite.config.ts中配置插件

    1. import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
    2. import path from 'path'
    3. export default () => {
    4. return {
    5. plugins: [
    6. vue(),
    7. createSvgIconsPlugin({
    8. // Specify the icon folder to be cached
    9. iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
    10. // Specify symbolId format
    11. symbolId: 'icon-[dir]-[name]'
    12. }),
    13. ]
    14. }
    15. }

    入口文件导入

    import 'virtual:svg-icons-register'

    svg封装为全局组件

    在src/components/SvgIcon目录下创建一个SvgIcon组件:代表如下

    1. <script setup lang="ts">
    2. defineProps({
    3. //xlink:href属性值的前缀
    4. prefix: {
    5. type: String,
    6. default: '#icon-'
    7. },
    8. //svg矢量图的名字
    9. name: String,
    10. //svg图标的颜色
    11. color: {
    12. type: String,
    13. default: ""
    14. },
    15. //svg宽度
    16. width: {
    17. type: String,
    18. default: '16px'
    19. },
    20. //svg高度
    21. height: {
    22. type: String,
    23. default: '16px'
    24. }
    25. })
    26. script>
    27. <style scoped>style>

    解决办法

    'vue/comment-directive': 'off',

    在src文件夹目录下创建一个index.ts文件:用于注册components文件夹内部全部全局组件!!!

    1. import SvgIcon from './SvgIcon/index.vue';
    2. import type { App, Component } from 'vue';
    3. const components: { [name: string]: Component } = { SvgIcon };
    4. export default {
    5. install(app: App) {
    6. Object.keys(components).forEach((key: string) => {
    7. app.component(key, components[key]);
    8. })
    9. }
    10. }

    在入口文件引入src/index.ts文件,通过app.use方法安装自定义插件

    1. import gloablComponent from './components/index';
    2. app.use(gloablComponent);

  • 相关阅读:
    Linux三大搜索指令的区别
    无名管道和有名管道
    MYSQL 查询重复数据
    【面试题】forEach能跳出循环吗?
    list的模拟实现
    实验:验证mysql索引失效场景
    第46屆ICPC 東亞洲區域賽(澳門)
    【日拱一卒行而不辍20220930】自制操作系统
    有限小数,进制转换,思维
    华为HMS Core携手超图为三维GIS注入新动能
  • 原文地址:https://blog.csdn.net/m0_52704461/article/details/133849854