vue2 参考代码:
vue2 的svg 配置
1. 安装 npm install svg-sprite-loader
npm install svg-sprite-loader
2. 配置 vue.config.js
const path = require("path");
function resolve(dir) {
return path.join(__dirname, dir);
}
module.exports = {
......
chainWebpack(config) {
config.module
.rule('svg')
.exclude.add(path.resolve('src/assets/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(path.resolve('src/assets/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
}
};
3. 封装svgIcon组件 scr/components/SvgIcon/index.vue
<template>
<svg :style="{ width, height }" aria-hidden="true">
<use :xlink:href="iconName" :fill="color" />
</svg>
</template>
<script>
export default {
name: "SvgIcon",
props: {
iconClass: {
type: String,
required: true,
},
className: {
type: String,
},
// 图标的颜色
color: {
type: String,
default: "",
},
// 接收父组件传递过来图标的宽高
width: {
type: String,
default: "16px",
},
height: {
type: String,
default: "16px",
},
},
computed: {
iconName() {
return `#icon-${this.iconClass}`;
},
},
};
</script>
<style scoped></style>
4. 创建 assets/icons/svg 用来放置svg图标 和 assets/icons/index.js 代码如下
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg component
// register globally
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
5. 在main.js引入icons/index.js
import './assets/icons/index.js'
6. 使用
<svg-icon icon-class="gongzuotai" width="30px" height="30px" color="red" />
7. fill="#000000" 变成 fill=""
8. 成果
vue3 参考代码
1. 安装SVG依赖插件
npm install vite-plugin-svg-icons -D
2. 在vite.config.ts中配置插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default () => {
return {
plugins: [
createSvgIconsPlugin({
// Specify the icon folder to be cached
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
// Specify symbolId format
symbolId: 'icon-[dir]-[name]',
}),
],
}
}
3. 在main.ts文件中全局导入
import 'virtual:svg-icons-register'
4. 在项目中引入SVG
4.1 在阿里字体图标库中复制svg代码
4.2 在assets/svg下有很多svg图片,其中一个名为qq.svg,在页面使用。如下代码,可见图即可
<template>
<div>
<div class="box">SVG测试</div>
<!--测试SVG图标使用-->
<!--svg:图标外层容器节点,内部需要与use标签结合使用-->
<svg style="width: 30px; height: 30px">
<!-- xlink:href执行用哪一个图标,属性值务必 #icon 图标名字 -->
<!-- use标签fill属性可以设置图标的颜色 -->
<use xlink:href="#icon-qq" fill="red"></use>
</svg>
</div>
</template>
5. svg封装为全局组件:src/components/CpIcon.vue
<template>
<svg aria-hidden="true" :width="width" :height="height" :fill="color">
<use :xlink:href="`#icon-${name}`" />
</svg>
</template>
<script setup lang="ts">
defineProps<{
name: string
width?: string
height?: string
color?: string
}>()
</script>
6. 在页面使用,见图即可成功
<template>
<CpIcon name="qq"></CpIcon>
</template>
<script setup lang="ts">
import CpIcon from '@/components/CpIcon.vue'
</script>