vue3中引入svg矢量图的实现示例
更新时间:2023年11月24日 15:57:06 作者:前端~初学者
在项目开发过程中,我们经常会用到svg矢量图,本文主要介绍了vue3中引入svg矢量图的实现示例,具有一定的参考价值,感兴趣的可以了解一下
1、前言
在项目开发过程中,我们经常会用到svg
矢量图,而且我们使用svg
以后,页面上加载的不再是图片资源,这对页面性能来说是个很大的提升,而且我们svg
文件比img
要小的很多,放在项目中几乎不占用资源。
2、安装SVG依赖插件
npm install vite-plugin-svg-icons -D 或 yarn add vite-plugin-svg-icons -D 或 pnpm install vite-plugin-svg-icons -D
3、在vite.config.ts 中配置插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons' import path from 'path' export default () => { return { plugins: [ createSvgIconsPlugin({ iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')], symbolId: 'icon-[dir]-[name]', }), ], } }
4、main.ts入口文件导入
import 'virtual:svg-icons-register'
5、使用svg
5.1 在src/assets/icons文件夹下引入svg矢量图
5.2 在src/components目录下创建一个SvgIcon组件
<template> <svg :style="{ width, height }"> <use :xlink:href="prefix + name" rel="external nofollow" :fill="color"></use> </svg> </template> <script setup> defineProps({ // 是否显示 prefix: { type: String, default: '#icon-', }, name: String, color: { type: String, default: '#000', }, width: { type: String, default: '16px', }, height: { type: String, default: '16px', }, }) </script> <style lang='scss' scoped></style>
5.3 封装成全局组件,在src文件夹下创建plugin/index.ts
//引入项目中的全局组件 import SvgIcon from '@/components/svgIcon.vue' //全局对象 const allGlobalComponents = { SvgIcon } //对外暴露插件对象 export default { install(app) { //注册项目的全部组件 Object.keys(allGlobalComponents).forEach((key) => { //注册为全局组件 app.component(key, allGlobalComponents[key]) }) }, }
5.4 在main.ts中引入plugin/index.ts文件
import GlobalComponents from '@/plugin' app.use(GlobalComponents)
5.5 在页面使用
<svg-icon name="tick" width="20px" height="20px"></svg-icon>
到此这篇关于vue3中引入svg矢量图的实现示例的文章就介绍到这了,更多相关vue3引入svg矢量图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
vue异步组件与组件懒加载问题(import不能导入变量字符串路径)
这篇文章主要介绍了vue异步组件与组件懒加载问题(import不能导入变量字符串路径),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-04-04vue + any-touch实现一个iscroll 实现拖拽和滑动动画效果
这篇文章主要介绍了vue + any-touch实现一个iscroll实现拖拽和滑动动画效果,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下2019-04-04
最新评论