当前位置: 首页 > news >正文

Vite创建Vue2项目中,封装svg-icon组件并使用——插件之vite-plugin-svg-icons和fast-glob

Vite创建Vue2项目中,封装svg-icon组件并使用——插件之vite-plugin-svg-icons和fast-glob

svg图片在项目中使用的非常广泛,vue2项目中进行引用

vite-plugin-svg-icons:

  • 预加载 在项目运行时就生成所有图标,只需操作一次 dom
  • 高性能 内置缓存,仅当文件被修改时才会重新生成

1、安装:

yarn add vite-plugin-svg-icons -D
# or
npm i vite-plugin-svg-icons -D
# or
pnpm install vite-plugin-svg-icons -D

2、配置

1、默认配置

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
   // 配置localhost
  server: {
		host: '0.0.0.0',
		port: 8080
	},
})

2、配置插件vite-plugin-svg-icons

// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import {createSvgIconsPlugin} from 'vite-plugin-svg-icons'
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    createSvgIconsPlugin({
      // 指定路径在你的src里的svg存放文件
      iconDirs: [path.resolve(process.cwd(), 'src/assets')],
      // 指定symbolId格式
      symbolId: '[name]'
    })
  ],
  server: {
		host: '0.0.0.0',
		port: 8080
	},
})

3、main.js中

src/main.js新增

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import 'virtual:svg-icons-register'  // 新增

createApp(App).mount('#app')

3、封装组件

3.1、封装组件

src\components\svgIcon.vue

<template>
  <svg :class="svgClass" aria-hidden="true">
    <use class="svg-use" :href="symbolId" :color="color"/>
    <title v-if="iconTitle">{{ iconTitle }}</title>
  </svg>
</template>
 
<script>
  import { defineComponent, computed } from 'vue'
 
  export default defineComponent({
    name: 'SvgIcon',
    props: {
      prefix: {
        type: String,
        default: 'icon'
      },
      name: {
        type: String,
        required: true
      },
      color: {
        type: String,
        default: '',
      },
      className: {
        type: String,
        default: ''
      },
      iconTitle: {
      type: String,
      default: '',
    },
    },
    setup(props) {
      const symbolId = computed(() => `#${props.name}`)
      const svgClass = computed(() => {
        if (props.className) {
          return `svg-icon ${props.className}`
        }
        return 'svg-icon'
      })
      return { symbolId, svgClass }
    }
  })
</script>
<style scope>
  .svg-icon { 
    vertical-align: -0.1em; /* 因icon大小被设置为和字体大小一致,而span等标签的下边缘会和字体的基线对齐,故需设置一个往下的偏移比例,来纠正视觉上的未对齐效果 */
    fill: currentColor; /* 定义元素的颜色,currentColor是一个变量,这个变量的值就表示当前元素的color值,如果当前元素未设置color值,则从父元素继承 */
    overflow: hidden;
  } 
</style>
3.2、页面使用

index.vue

<script setup>
import { ref } from 'vue'

import SvgIcon from "./svgIcon.vue";  // 引用组件

defineProps({
  msg: String
})

const count = ref(0)
</script>

<template>
<!-- 使用组件 -->
 <SvgIcon name="layer" color="red" icon-title="svg图标提示语" class-name="menu-svg-icon"></SvgIcon>
 <div v-if="false">
  <h1>{{ msg }}</h1>
  <div class="card">
    <button type="button" @click="count++">count is {{ count }}</button>
  </div>
 </div>
</template>

<style scoped>
.read-the-docs {
  color: #888;
}
.menu-svg-icon{
    height:124px;
    width:124px;
    color:blue;
}
</style>
  • color参数的权重高于class-name参数设置的css样式颜色权重

npm run dev,运行项目时,显示缺少依赖包,报错

在这里插入图片描述

安包,并再次运行项目

npm i fast-glob

显示svg如下

在这里插入图片描述

4.1、按需引入使用

index.vue

<template>
    <svg-icon
      :name="nameVal"
      color="blue"
      class-name="menu-svg-icon"
      :icon-title="iconTitle"
    ></svg-icon>
    <!-- <SvgIcon name="layer" color="red" icon-title="svg图标提示语" class-name="menu-svg-icon"></SvgIcon> -->
</template>
 
<script setup>
import SvgIcon from "@/components/SvgIcon.vue";
    
let iconTitle = ref('svg图片')
// let colorVal = ref('blue')
let nameVal= ref('layer')
</script>

<style scoped>
.menu-svg-icon{
  width: 180px;
  height: 180px;
  color: red !important
}
</style>

4.2、全局引入使用

在main.js中加入

初始版

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import 'virtual:svg-icons-register'  // 插件引入
 

createApp(App).mount('#app') // 挂载组件

src/main.js

import { createApp } from 'vue'
import './style.css'
import svgIcon from './components/svgIcon.vue'  // 引入
import App from './App.vue'
import 'virtual:svg-icons-register'
 

createApp(App).component('SvgIcon', svgIcon).mount('#app') // 挂载组件

页面使用

<template>
    <svg-icon
      :name="nameVal"
      color="blue"
      class-name="menu-svg-icon"
      :icon-title="iconTitle"
    ></svg-icon>
    <!-- <SvgIcon name="layer" color="red" icon-title="svg图标提示语" class-name="menu-svg-icon"></SvgIcon> -->
</template>
 
<script setup>   
  let iconTitle = ref('svg图片')
  // let colorVal = ref('blue')
  let nameVal= ref('layer')
</script>

<style scoped>
.menu-svg-icon{
  width: 180px;
  height: 180px;
  color: red !important
}
</style>

相关文章:

  • 洛谷题单 Part2.1 模拟
  • Selenium 中的 JUnit 注解
  • ES6中的set、map
  • 基python的毕业设计题目超市进存销系统
  • 云计算基础
  • C语言文件基本操作
  • 2022年全球及中国疏水阀行业头部企业市场占有率及排名调研报告
  • java6.2 springCloud
  • 第6章Linux实操篇-开机、重启和用户登录注销
  • 大学网课答案微信公众号接口使用方法
  • 第5章Linux实操篇-Vi和Vim编辑器
  • java6.1 springboot
  • Linux高性能服务器之I/O复用之实例 ET AND LT(图像理解)(14)
  • 计算机毕业设计django基于python大学生心理健康系统(源码+系统+mysql数据库+Lw文档)
  • java计算机毕业设计个性化推荐的扬州农业文化旅游管理平台源码+数据库+系统+lw文档+mybatis+运行部署
  • 深入了解以太坊
  • 2017-08-04 前端日报
  • IE报vuex requires a Promise polyfill in this browser问题解决
  • Intervention/image 图片处理扩展包的安装和使用
  • Laravel 实践之路: 数据库迁移与数据填充
  • MyEclipse 8.0 GA 搭建 Struts2 + Spring2 + Hibernate3 (测试)
  • Python打包系统简单入门
  • Twitter赢在开放,三年创造奇迹
  • vue从创建到完整的饿了么(11)组件的使用(svg图标及watch的简单使用)
  • WordPress 获取当前文章下的所有附件/获取指定ID文章的附件(图片、文件、视频)...
  • 缓存与缓冲
  • 讲清楚之javascript作用域
  • 聊聊hikari连接池的leakDetectionThreshold
  • 七牛云假注销小指南
  • 前端技术周刊 2019-02-11 Serverless
  • 一个SAP顾问在美国的这些年
  • 原生Ajax
  • media数据库操作,可以进行增删改查,实现回收站,隐私照片功能 SharedPreferences存储地址:
  • Java性能优化之JVM GC(垃圾回收机制)
  • ​​​​​​​GitLab 之 GitLab-Runner 安装,配置与问题汇总
  • #每天一道面试题# 什么是MySQL的回表查询
  • (11)MSP430F5529 定时器B
  • (2)STL算法之元素计数
  • (day6) 319. 灯泡开关
  • (javascript)再说document.body.scrollTop的使用问题
  • (四)【Jmeter】 JMeter的界面布局与组件概述
  • (五) 一起学 Unix 环境高级编程 (APUE) 之 进程环境
  • (转载)CentOS查看系统信息|CentOS查看命令
  • .aanva
  • .net core IResultFilter 的 OnResultExecuted和OnResultExecuting的区别
  • .net(C#)中String.Format如何使用
  • .NET6实现破解Modbus poll点表配置文件
  • .NET程序员迈向卓越的必由之路
  • .net利用SQLBulkCopy进行数据库之间的大批量数据传递
  • .NET轻量级ORM组件Dapper葵花宝典
  • /usr/bin/env: node: No such file or directory
  • @ComponentScan比较
  • @select 怎么写存储过程_你知道select语句和update语句分别是怎么执行的吗?
  • [Android 数据通信] android cmwap接入点
  • [AutoSar]状态管理(五)Dcm与BswM、EcuM的复位实现