vue项目中使用SVG-ICON

其他好文章 https://blog.csdn.net/qq_38974163/article/details/119135848

1.webpack.base.conf中配置svg的依赖和loader

    {
            test: /\.svg$/,
            loader: 'svg-sprite-loader',
            include: [resolve('src/icon')],
            options: {
                symbolId: 'icon-[name]'
            }
       },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        exclude: [resolve('src/icons')],
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },

2.插入svg-sprite-loader包 npm i svg-sprite-loader

3.在src文件夹下创建icon文件夹 结构如下:

 4.icon中index.js

import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg组件
 
// register globally
Vue.component('svg-icon', SvgIcon)
 
const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('./svg', false, /\.svg$/)
requireAll(req)

5.写一个全局组建SvgIcon

<template>
  <svg class="svg-icon" aria-hidden="true">
    <use :xlink:href="iconName"></use>
  </svg>
</template>
 
<script>
export default {
  name: 'SvgIcon',
  props: {
    iconClass: {
      type: String,
      required: true
    }
  },
  computed: {
    iconName() {
      return `#icon-${this.iconClass}`
    }
  }
}
</script>
 
<style>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>
 

6.main.js中引入icon

7.在vue文件中使用

<svg-icon  icon-class="search" />
posted @ 2022-06-09 14:35  前端小沫  阅读(727)  评论(0编辑  收藏  举报