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的颜色
相关文章
|
1月前
Vue3中getCurrentInstance如何与ts结合使用
【8月更文挑战第16天】Vue3中getCurrentInstance如何与ts结合使用
91 2
Vue3中getCurrentInstance如何与ts结合使用
|
25天前
|
存储 JavaScript
解锁Vuex高级玩法:模块化与插件共舞,让你的Vue项目状态管理如虎添翼!
【8月更文挑战第27天】Vuex是一款专为Vue.js应用程序设计的状态管理模式及库,它通过集中管理组件状态来确保状态变更的可预测性。在大型应用中,采用模块化管理可以让代码结构更加清晰,同时利用插件增强功能。模块化管理允许将store拆分为包含各自state、mutations、actions和getters的独立模块。插件则能监听状态变化,实现诸如日志记录或数据持久化等功能。本文通过具体示例介绍了如何在Vuex中实现模块化管理和插件的高级应用。
34 1
|
1月前
|
JavaScript
如何创建一个Vue项目(手把手教你)
这篇文章是一篇手把手教读者如何创建Vue项目的教程,包括使用管理员身份打开命令行窗口、找到存放项目的位置、通过vue-cli初始化项目、填写项目信息、进入项目目录、启动项目等步骤,并提供了一些常见第三方库的引入方法。
如何创建一个Vue项目(手把手教你)
|
11天前
|
前端开发
vue3+ts项目中使用mockjs
vue3+ts项目中使用mockjs
216 58
|
3天前
|
JavaScript 前端开发
Vue项目使用px2rem
Vue项目使用px2rem
|
8天前
|
JavaScript 开发工具
vite如何打包vue3插件为JSSDK
【9月更文挑战第10天】以下是使用 Vite 打包 Vue 3 插件为 JS SDK 的步骤:首先通过 `npm init vite-plugin-sdk --template vue` 创建 Vue 3 项目并进入项目目录 `cd vite-plugin-sdk`。接着,在 `src` 目录下创建插件文件(如 `myPlugin.js`),并在 `main.js` 中引入和使用该插件。然后,修改 `vite.config.js` 文件以配置打包选项。最后,运行 `npm run build` 进行打包,生成的 `my-plugin-sdk.js` 即为 JS SDK,可在其他项目中引入使用。
|
7天前
|
JavaScript 前端开发
Vue项目使用px2rem
Vue项目使用px2rem
|
9天前
|
JavaScript 前端开发 UED
让 HTML 向 Vue.js 华丽转身:如何把 `wangEditor` 仿腾讯文档项目整合进 Vue.js
让 HTML 向 Vue.js 华丽转身:如何把 `wangEditor` 仿腾讯文档项目整合进 Vue.js
|
14天前
|
数据采集 JavaScript 搜索推荐
我们一起聊聊如何对Vue项目进行搜索引擎优化
【9月更文挑战第4天】Vue 项目的搜索引擎优化(SEO)较为复杂,因其内容默认由 JavaScript 渲染,部分搜索引擎难以索引。为提升 SEO 效果,可采用服务器端渲染(SSR)或预渲染,使用 Nuxt.js 或 Vue Server Renderer 实现 SSR,或利用 Prerender SPA Plugin 预渲染静态 HTML。此外,动态管理 Meta 标签、优化静态内容与 Sitemap、懒加载、图片优化、提升页面速度、设置正确的路由模式、使用结构化数据及构建良好外链均有益于 SEO。
43 11
|
1月前
|
JavaScript
Vue项目如何生成树形目录结构
这篇文章介绍了如何在Vue项目中生成树形目录结构,通过安装并使用`mddir`命令行工具来创建一个`directoryList.md`文件,从而快速获取项目的树形目录列表。
Vue项目如何生成树形目录结构