项目使用版本Vue3.x
- 安装依赖
npm i svg-sprite-loader -D
- 自定义svg-icon组件
src/components新建SvgIcon文件夹,在SvgIcon中新建文件index.vue
<template>
<div v-if="isExternal"
:style="styleExternalIcon"
class="svg-external-icon svg-icon"
v-bind="$attrs" />
<svg v-else
:class="svgClass"
aria-hidden="true"
v-bind="$attrs">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
import {
computed
} from 'vue';
export default {
name: "SvgIcon",
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ''
}
},
setup(props) {
const isExternal = computed(() => {
return /^(https?:|mailto:|tel:)/.test(props.iconClass);
})
const iconName = computed(() => {
return `#icon-${props.iconClass}`;
})
const svgClass = computed(() => {
if (props.className) {
return `svg-icon ${props.className}`
}
return 'svg-icon'
})
const styleExternalIcon = computed(() => {
return {
mask: `url(${props.iconClass}) no-repeat 50% 50%`,
'-webkit-mask': `url(${props.iconClass}) no-repeat 50% 50%`
};
})
return {
isExternal,
iconName,
svgClass,
styleExternalIcon
}
}
}
</script>
<style scoped>
.svg-icon {
fill: currentColor;
height: 1em;
overflow: hidden;
vertical-align: -0.15em;
width: 1em;
}
.svg-external-icon {
background-color: currentColor;
display: inline-block;
mask-size: cover !important;
}
</style>
- 新建svg文件的存放目录
1、在src下新建icons文件夹,文件夹里再新建svg文件夹,将svg图片放至svg文件夹里
2、在src/icons文件夹,新建index.js文件
import SvgIcon from '@/components/SvgIcon' // svg component
/**
* 一次性的引入某个文件夹下的所有文件
* require.context(directory, useSubdirectories,regExp)
* 形参:
* directory:需要引入文件的目录
* useSubdirectories:是否查找该目录下的子级目录
* regExp:匹配引入文件的正则表达式
*/
const registerSvgIcon = (app) => {
app.component('svg-icon', SvgIcon) // 注册全局组件
const req = require.context('./svg', false, /\.svg$/);
const requireAll = requireContext => requireContext.keys().map(requireContext);
requireAll(req);
}
export default registerSvgIcon;
- main.js 中引入
import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'
import registerSvgIcon from './icons';
const app = createApp(App)
app
.use(router)
.mount('#app')
registerSvgIcon(app)
- 修改vue.config.js
const path = require('path')
const defaultSettings = require('./src/settings.js')
const resolve = dir => path.join(__dirname, dir)
const name = defaultSettings.name || 'demo' // page title
// port = 8000 npm run serve OR npm run serve --port = 8000
const port = process.env.port || process.env.npm_config_port || 8000 // dev port
const pages = {
index: {
entry: 'src/main.js',
template: 'public/index.html',
filename: 'index.html',
chunks: ['chunk-vendors', 'chunk-common', 'index']
}
}
module.exports = {
pages,
publicPath: '/vue3/',
outputDir: 'dist',
assetsDir: 'static',
productionSourceMap: false, // 去除打包后产生的map文件
devServer: {
port,
open: true,
overlay: {
warnings: false,
errors: true
},
proxy: {
'/api': {
target: 'http://localhost:3000',
pathRewrite: {
'^/api': ''
}
}
}
},
configureWebpack: {
// 在index.html中注入正确的title
name,
resolve: {
alias: {
'@': resolve('src') // 设置路径别名
}
}
},
chainWebpack (config) {
// 多页面打包时,需循环处理, 提高首屏的加载速度
Object.keys(pages).forEach((page) => {
config.plugin(`preload-${page}`).tap(() => [
{
rel: 'preload',
// to ignore runtime.js
fileBlackList: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
include: 'initial'
}
])
})
// set svg-sprite-loader
config.module
.rule('svg')
.exclude.add(resolve('src/icons'))
.end();
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]',
})
.end()
}
};
- 页面使用
<template>
<div>
<svg-icon icon-class="imgCode" :style="mySvg"/>
<svg-icon icon-class="购物车" :style="mySvg"/>
</div>
</template>
<script>
import {
reactive
} from "vue"
export default {
name: 'SvgTest',
setup() {
const mySvg = reactive({
width: '200px',
height: '100px'
})
return {
mySvg
}
}
}
</script>