zoukankan      html  css  js  c++  java
  • vue-在公共icon封装组件里使用svg图标

    1.安装svg-sprite-loader。package.json:"svg-sprite-loader": "^3.9.2",

    2.build/webpack.base.conf.js的model.rules新增配置:

    {
            test: /.svg$/,
            loader: 'svg-sprite-loader',
            include: [resolve('src/icons')],
            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]')
            }
          },

    3.components下新建SvgIcon/index.vue文件,内容:

    <template>
    <svg :class="svgClass" aria-hidden="true">
        <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 {
        width: 1em;
        height: 1em;
        vertical-align: -0.15em;
        fill: currentColor;
        overflow: hidden;
    }
    </style>

    4.src下新建icons/svg文件夹和icons/index.js文件,前者放置所有.svg文件,后者内容为:

    import Vue from 'vue'
    import SvgIcon from '@/components/SvgIcon'// 引入svg组件
    
    // 注册全局组件
    Vue.component('svg-icon', SvgIcon)
    // require.context,通过正则匹配到可能的文件,全部引入
    const req = require.context('./svg', false, /.svg$/)
    const requireAll = requireContext => requireContext.keys().map(requireContext)
    requireAll(req)

    5.在main.js中引入的公共js文件里引入icons下所有文件:

    import '@/icons'

    6.页面使用,icon-class就是之前存放在src/svg下的各个.svg文件名称:

    <svg-icon icon-class="warning" />
    <svg-icon icon-class="why" />

    放个链接

  • 相关阅读:
    CSS 之 @media
    How to fix “Duplicate sources.list entry …” issue
    shell脚本加不加export的区别
    过滤部分错误信息,不输出到stderr
    /dev/null 2>&1 解释(转)
    crontab与环境变量
    PHP实现斐波那契数列非递归方法
    有反斜杠时候,CakePHP往pgsql插入数据异常
    PHP输出图片文件,实现浏览器缓存机制
    sudo: unable to resolve host XXX 解决方法
  • 原文地址:https://www.cnblogs.com/wd163/p/14107556.html
Copyright © 2011-2022 走看看