vue中使用svg图片

vue通过vite-plugin-svg-icons插件使用SVG图片

一、安装

npm install vite-plugin-svg-icons -D
or 
yarn add vite-plugin-svg-icons -D

二、配置vite.config.js文件

import {createSvgIconsPlugin} from 'vite-plugin-svg-icons'

export default defineConfig({
    ...
    plugins:[createSvgIconsPlugin({
        //指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(),'src/assets/icons/svg')],
        // 指定symbolId格式
        symbolId: 'icon-[name]'
    })],
    ...
})

(对应svg图片存放位置) 

 三、在main.js引入

import 'virtual:svg-icons-register'

四、封装svg组件(我的路径:src/components/SvgIcon/index.vue)

<template>
  <svg aria-hidden="true" class="svg-icon">
    <use :xlink:href="symbolId" />
  </svg>
</template>

<script setup>
import { computed } from "vue";
const props = defineProps({
  prefix: {
    type: String,
    default: "icon",
  },
  name: {
    type: String,
    required: true,
  },
});

const symbolId = computed(() => `#${props.prefix}-${props.name}`);
</script>

<style scope>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

五、页面使用

       1、按需引用

<template>
  <SvgIcon name="user"></SvgIcon>
</template>
<script setup>
import SvgIcon from "@/components/SvgIcon/index.vue";
</script>

        2、全局引用

import SvgIcon from './components/SvgIcon/index.vue'

createApp(App).component("SvgIcon",SvgIcon)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值