1、安装 svg-sprite-loader
yarn add svg-sprite-loader
2、nuxt.config.js中的build配置相关打包信息
config.module.rules.push({
test: /.svg$/,
loader: 'svg-sprite-loader',
include: [path.join(__dirname, 'src', 'assets', 'svg')],
options: {
symbolId: 'icon-[name]',
},
})
3、plugins中简历svg-icon.js,并在nuxt.config.js配置plugin信息
svg-icon.js
import Vue from 'vue'
import SvgIcon from '@/components/svg-icon' // svg component
// register globally
Vue.component('svg-icon', SvgIcon)
const req = require.context('@/assets/svg', false, /.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
nuxt.config.js
plugins: [
{src: '~plugins/axios-inject'},
{src: '~plugins/axios'},
{src: '~plugins/filters'},
{src: '~plugins/element'},
{src: '~plugins/icon-font'},
{src: '~plugins/svg-icon'},
'~plugins/composition-api',
'~plugins/global-mixin',
'~plugins/analysis',
'~plugins/sentry',
],
4.svg-icon组件
<template>
<div
v-if="isExternal && iconClass"
:style="styleExternalIcon"
class="svg-external-icon svg-icon"
v-on="$listeners"
/>
<svg v-else :class="svgClass" aria-hidden="true" v-on="$listeners">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
// doc: https://panjiachen.github.io/vue-element-admin-site/feature/component/svg-icon.html#usage
// import { isExternal } from '@/utils/validate'
/**
* @param {string} path
* @returns {Boolean}
*/
export function isExternal(path) {
return /^(https?:|mailto:|tel:)/.test(path)
}
export default {
name: 'SvgIcon',
props: {
iconClass: {
type: String,
default: '',
},
className: {
type: String,
default: '',
},
},
computed: {
isExternal() {
return isExternal(this.iconClass)
},
iconName() {
return `#icon-${this.iconClass}`
},
svgClass() {
if (this.className) {
return `svg-icon ${this.className}`
} else {
return 'svg-icon'
}
},
styleExternalIcon() {
return {
mask: `url(${this.iconClass}) no-repeat 50% 50%`,
'-webkit-mask': `url(${this.iconClass}) no-repeat 50% 50%`,
}
},
},
}
</script>
<style scoped>
.svg-icon {
1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
.svg-external-icon {
background-color: currentColor;
mask-size: cover !important;
display: inline-block;
}
</style>