环境
"nuxt": "^2.15.7",
"nuxt-svg-sprite-loader": "^2.0.9",
准备工作
一、安装nuxt-svg-sprite-loader插件
npm install nuxt-svg-sprite-loader
二、创建SVG组件文件
<template>
<client-only>
<svg :style="{
width:width+'px',
height:height+'px',
fill:color
}"
:class="['svg-icon', svgClass]"
aria-hidden="true">
<use :xlink:href="svgName"></use>
</svg>
</client-only>
</template>
<script>
export default {
name: "svgIcon",
props: {
iconName: {
type: String,
default: "",
},
className: {
type: String,
default: "",
},
color: {
type: String,
default: "#A1A1A1",
},
width: {
type: String,
default: "16",
},
height: {
type: String,
default: "16",
},
},
computed: {
svgName () {
return `#icon-${this.iconName}`;
},
svgClass () {
if (this.className) {
return ` ${this.className}`;
}
},
},
};
</script>
<style lang="scss" scoped>
</style>
三、填写插件(全局引入组件,解析所有.svg文件)
#首先要在assets文件夹下创建一个名为svg文件夹把所有svg文件放进去
import Vue from "vue";
import svgIcon from "@/components/comm/SvgIcon.vue";
Vue.component("svg-icon", svgIcon);
const req = require.context("@/assets/svg", false, /\.svg$/);
const requireAll = requireContext => {
return requireContext.keys().map(requireContext)
}
requireAll(req);
四、nuxt.config.js 添加插件和打包规则
export default {
modules: [
['nuxt-svg-sprite-loader', {
symbolId: 'icon-[name]'
}],
]
}
使用
<svg-icon width="20"
height="20"
color="red"
iconName='play'
className="play"></svg-icon>