首先创建一个 index.vue 新组件
<template>
<svg
class="svg-icon"
:class="svgClass"
:style="{ width: width + 'px', height: height + 'px' }"
aria-hidden="true"
>
<use :xlink:href="iconName" />
</svg>
</template>
<script>
export default {
name: "SvgIcon",
props: {
name: {
type: String,
required: true,
},
width: {
type: Number,
default: 40,
},
height: {
type: Number,
default: 40,
},
},
computed: {
iconName() {
return `#icon-${this.name}`;
},
svgClass() {
if (this.name) {
return "svg-icon" + this.name;
} else {
return "svg-icon";
}
},
},
};
</script>
<style scoped>
.svg-icon {
width: 100px;
height: 100px;
fill: currentColor;
overflow: hidden;
}
</style>
其次要注册该组件
import Vue from 'vue'
import SvgIcon from './index.vue' // 引用新组件
// register globally
Vue.component('svg-icon', SvgIcon)
const req = require.context('@/assets/svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
最后直接在vue文件使用
<svg-icon
name="kafkasource"
:width="14"
:height="12"
/>
// name表示命名的svg图标文件名称
// width、height表示图标大小