使用 svg-sprite-loader(雪碧图方案)
合并所有 SVG 为单个雪碧图,通过 <use>
引用。
安装依赖
npm install svg-sprite-loader --save-dev
配置 vue.config.js
const { defineConfig } = require('@vue/cli-service')
const path = require('path')
module.exports = defineConfig({
chainWebpack: (config) => {
// 默认 SVG 规则排除 icons 目录
config.module
.rule('svg')
.exclude.add(path.resolve(__dirname, 'src/assets/svgs'))
.end();
// 添加 svgs 目录专属规则
config.module
.rule('svgs')
.test(/\.svg$/)
.include.add(path.resolve(__dirname, 'src//assets/svgs'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({ symbolId: 'icon-[name]' }); // symbolId 命名规则
}
})
创建全局组件 SvgIcon.vue
<template>
<svg>
<use :xlink:href="`#icon-${name}`" x="0" y="0" />
</svg>
</template>
<script>
export default {
props: {
name: { type: String, required: true }, // SVG 文件名
}
};
</script>
在入口文件(如 main.js
)自动导入所有 SVG
const req = require.context('@/assets/svgs', false, /\.svg$/);
req.keys().map(req);
组件中使用
<template>
<div>
svg:<SvgIcon name="enter" class="svg-icon" />
</div>
</template>
<script>
import SvgIcon from '@/views/SvgIcon.vue';
export default {
components: { SvgIcon }
}
</script>
<style lang="scss" scoped>
.svg-icon {
width: 40px;
height: 40px;
fill: currentColor;
color: black;
&:hover {
color: red;
}
}
</style>
注意这里设置了 svg 图片 :hover 要想生效必须将 svg 里 fill="rgb" 颜色设为 fill="currentColor" 或是删除这个属性。
也可以注册为全局组件
Vue.component('SvgIcon', SvgIcon)
可以下载一个 svg 图片命名为 enter.svg 放到 assets/svgs 目录下
启动网站