前端开发之中svg图标的利用和实例

水军大提督  论坛元老 | 2024-6-13 07:33:05 | 来自手机 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1599|帖子 1599|积分 4797

前言

svg图片我们可在阿里云矢量图标库中下载
阿里云矢量图标库
效果图



1、安装插件

   npm i svg-sprite-loader --save
  2、vue3中利用

2.1、 在components文件夹中,创建公共类SvgIcon/index.vue


  1. <template>
  2.   <svg :class="svgClass" aria-hidden="true">
  3.     <use :xlink:href="iconName" />
  4.   </svg>
  5. </template>
  6. <script>
  7. export default {
  8.   name: 'SvgIcon',
  9.   props: {
  10.     iconClass: {
  11.       type: String,
  12.       required: true
  13.     },
  14.     className: {
  15.       type: String,
  16.       default: ''
  17.     }
  18.   },
  19.   computed: {
  20.     iconName () {
  21.       return `#icon-${this.iconClass}`
  22.     },
  23.     svgClass () {
  24.       if (this.className) {
  25.         return 'svg-icon ' + this.className
  26.       } else {
  27.         return 'svg-icon'
  28.       }
  29.     },
  30.     styleExternalIcon () {
  31.       return {
  32.         mask: `url(${this.iconClass}) no-repeat 50% 50%`,
  33.         '-webkit-mask': `url(${this.iconClass}) no-repeat 50% 50%`
  34.       }
  35.     }
  36.   }
  37. }
  38. </script>
  39. <style scoped>
  40. .svg-icon {
  41.   width: 1.5em;
  42.   height: 1.5em;
  43.   vertical-align: -0.15em;
  44.   fill: currentColor;
  45.   overflow: hidden;
  46. }
  47. .svg-external-icon {
  48.   background-color: currentColor;
  49.   mask-size: cover!important;
  50.   display: inline-block;
  51. }
  52. </style>
复制代码
2.2、创建icons文件,存放svg图标和将所有的svg图标举行引用并注册成全局组件


  1. // 导入 Vue 框架
  2. import {
  3.     createApp } from 'vue'
  4. import App from '../App.vue'
  5. // 导入 SvgIcon 组件
  6. import SvgIcon from '@/components/svgIcon/index.vue'
  7. // 将 SvgIcon 组件注册为全局组件
  8. const app = createApp(App)
  9. app.component('svg-icon', SvgIcon)
  10. // 定义一个函数,用于引入所有 svg 文件
  11. const requireAll = requireContext => requireContext.keys().map(requireContext)
  12. // 定义一个上下文,只包含 './svg' 目录下的以 '.svg' 结尾的文件
  13. const req = require.context('./svg', false, /\.svg$/)
  14. // 引入 svg 文件
  15. requireAll(req)
  16. app.mount('#app')
复制代码
2.3、在man.js 中注册


  1. import svgIcon from '@/components/svgIcon/index.vue'
  2. import './icons/index.js'
  3. app.component('svg-icon', svgIcon)
复制代码
2.4、


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

水军大提督

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表