zoukankan      html  css  js  c++  java
  • vue-cli3引入svg图标全过程以及遇到的坑

    https://blog.csdn.net/weixin_41229588/article/details/101159755

    一、配置

    1.安装依赖:

    npm install svg-sprite-loader --save-dev

    2.配置build文件夹中的webpack.base.conf.js,主要在两个地方添加代码,如下图所示

    exclude: [resolve('src/icons')],
    复制代码
    {
            test: /.svg$/,
            loader: 'svg-sprite-loader',
            include: [resolve('src/icons')],
            options: {
              symbolId: 'icon-[name]'
            }
          },
    复制代码

     

    3.在src/components下新建文件夹及文件SvgIcon/index.vue,index.vue中内容如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    <template>
      <svg :class="svgClass" aria-hidden="true" v-on="$listeners">
        <use :xlink:href="iconName"/>
      </svg>
    </template>
     
    <script>
      export default {
        name: 'SvgIcon',
        props: {
          iconClass: {
            type: String,
            required: true
          },
          className: {
            type: String,
            default''
          }
        },
        computed: {
          iconName() {
            return `#icon-${this.iconClass}`
          },
          svgClass() {
            if (this.className) {
              return 'svg-icon ' this.className
            else {
              return 'svg-icon'
            }
          }
        }
      }
    </script>
     
    <style scoped>
      .svg-icon {
         1em;
        height: 1em;
        vertical-align: -0.15em;
        fill: currentColor;
        overflow: hidden;
      }
    </style>

    4.在src下新建icons文件夹,及icons文件夹下svg文件夹、index.js文件, index.js文件内容如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    import Vue from 'vue'
    import SvgIcon from '@/components/SvgIcon'// svg组件
     
    // register globally
    Vue.component('svg-icon', SvgIcon)
     
    const req = require.context('./svg'false, /.svg$/)
    const requireAll = requireContext => requireContext.keys().map(requireContext)
    requireAll(req)

    5.在main.js中引入svg

    import './icons'

    二、使用

    1.下载svg图片,这里使用阿里云提供的iconfont:https://www.iconfont.cn/collections/index?spm=a313x.7781069.1998910419.4&type=1

    2.点击图片,下载svg格式即可,将下载下来的图片放置到到项目中的svg文件夹下

    3.在页面中使用

    <svg-icon icon-class="test"></svg-icon>

  • 相关阅读:
    读书日记-策略模式
    五、@property的参数
    三、Object-C内存管理
    二、OC的构造方法和descriprtion方法
    一、初始Object-C
    linux中安装eclipse--CnetOS6.5
    linux中安装和配置 jdk
    linux中安装mysql
    bzip2压缩 解压缩
    gzip压缩解压缩
  • 原文地址:https://www.cnblogs.com/xzybk/p/12589045.html
Copyright © 2011-2022 走看看