vue3+vite+ts项目中使用svg图标

简介: vue3+vite+ts项目中使用svg图标

项目结构


网络异常,图片无法展示
|


1. 首先引入svg插件


yarn add svg-sprite-loader -D
// 或者
npm install svg-sprite-loader -D
复制代码


网络异常,图片无法展示
|


2. 创建文件


@/src里面创建icons文件夹,里面创建index.vue(svgicon的模板文件), index.ts(svgicon的js逻辑), svg文件夹(svg图标存放的地址)


index.vue(svgicon的模板文件)


这部分需要用到fs模块,所以需要:


yarn add fs
// 或者
npm install fs
复制代码


<template>
    <svg :class="svgClass" v-bind="$attrs" :style="{ color: color }">
        <use :xlink:href="iconName"></use>
    </svg>
</template>
<script setup lang="ts">
import { computed, defineProps } from 'vue'
const props = defineProps({
    name: {
        type: String,
        required: true
    },
    color: {
        type: String,
        default: ''
    }
})
const iconName = computed(() => `#icon-${ props.name }`)
const svgClass = computed(() => {
    if(props.name) return `svg-icon icon-${ props.name }`
    return 'svg-icon'
})
</script>
<style scoped>
.svg-icon{width: 1em;height: 1em;fill:currentColor; vertical-align: middle;}
</style>
复制代码


index.ts(svg的js逻辑文件)


这部分有问题的小伙伴可以找我,我写了注释的。


import { readFileSync, readdirSync } from 'fs'
let idPerfix = ''
const svgTitle = /<svg([^>+].*?)>/
const clearHeightWidth = /(width|height)="([^>+].*?)"/g
const hasViewBox = /(viewBox="[^>+].*?")/g
const clearReturn = /(\r)|(\n)/g
// 查找svg文件
function svgFind(e) {
  const arr = []
  const dirents = readdirSync(e, { withFileTypes: true })
  for (const dirent of dirents) {
    if (dirent.isDirectory()) arr.push(...svgFind(e + dirent.name + '/'))
    else {
        const svg = readFileSync(e + dirent.name)
                    .toString()
                    .replace(clearReturn, '')
                    .replace(svgTitle, ($1, $2) => {
                            let width = 0,
                                height = 0,
                                content = $2.replace(clearHeightWidth, (s1, s2, s3) => {
                                    if (s2 === 'width') width = s3
                                    else if (s2 === 'height') height = s3
                                    return ''
                                })
                if (!hasViewBox.test($2)) content += `viewBox="0 0 ${width} ${height}"`
                return `<symbol id="${idPerfix}-${dirent.name.replace('.svg', '')}" ${content}>`
        }).replace('</svg>', '</symbol>')
        arr.push(svg)
    }
  }
  return arr
}
// 生成svg
export const createSvg = (path: any, perfix = 'icon') => {
  if (path === '') return
  idPerfix = perfix
  const res = svgFind(path)
  return {
    name: 'svg-transform',
    transformIndexHtml(dom: String) {
        return dom.replace(
            '<body>',
            `<body><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0">${res.join('')}</svg>`
        )
    }
  }
}
复制代码


svg存放svg图标


网络异常,图片无法展示
|


3. 在vite.config.ts里面引用svg


import { defineConfig } from "vite"
import { createSvg } from './src/icons/index'
export default defineConfig({
    plugins: [
      vue(),
      createSvg('./src/icons/svg/')
     ]
})
复制代码


4. 在main.ts中写入svg-icon模板


import { createApp } from 'vue'
import App from './App.vue'
import svgIcon from './icons/index.vue'
const app = createApp(App)
app
.component('svg-icon', svgIcon)
.mount('#app')
复制代码


酱紫,就可以啦。(用法)


网络异常,图片无法展示
|


  • name是svg的名称
  • color是svg的颜色
相关文章
|
6月前
|
JavaScript 前端开发 安全
Vue 3
Vue 3以组合式API、Proxy响应式系统和全面TypeScript支持,重构前端开发范式。性能优化与生态协同并进,兼顾易用性与工程化,引领Web开发迈向高效、可维护的新纪元。(238字)
916 139
|
6月前
|
缓存 JavaScript 算法
Vue 3性能优化
Vue 3 通过 Proxy 和编译优化提升性能,但仍需遵循最佳实践。合理使用 v-if、key、computed,避免深度监听,利用懒加载与虚拟列表,结合打包优化,方可充分发挥其性能优势。(239字)
510 1
|
7月前
|
开发工具 iOS开发 MacOS
基于Vite7.1+Vue3+Pinia3+ArcoDesign网页版webos后台模板
最新版研发vite7+vue3.5+pinia3+arco-design仿macos/windows风格网页版OS系统Vite-Vue3-WebOS。
816 11
|
6月前
|
JavaScript 安全
vue3使用ts传参教程
Vue 3结合TypeScript实现组件传参,提升类型安全与开发效率。涵盖Props、Emits、v-model双向绑定及useAttrs透传属性,建议明确声明类型,保障代码质量。
572 0
|
JavaScript 前端开发
重读vue电商网站45之项目优化上线
重读vue电商网站45之项目优化上线
244 0
重读vue电商网站45之项目优化上线
|
JavaScript Java 物联网
现有vue项目seo优化
现有vue项目seo优化
|
7月前
|
JavaScript
Vue中如何实现兄弟组件之间的通信
在Vue中,兄弟组件可通过父组件中转、事件总线、Vuex/Pinia或provide/inject实现通信。小型项目推荐父组件中转或事件总线,大型项目建议使用Pinia等状态管理工具,确保数据流清晰可控,避免内存泄漏。
649 2
|
6月前
|
缓存 JavaScript
vue中的keep-alive问题(2)
vue中的keep-alive问题(2)
548 137
|
10月前
|
人工智能 JavaScript 算法
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
1079 0
|
10月前
|
JavaScript UED
用组件懒加载优化Vue应用性能
用组件懒加载优化Vue应用性能

热门文章

最新文章

下一篇
开通oss服务