美文网首页
vue 使用svg

vue 使用svg

作者: 半夜成仙 | 来源:发表于2022-01-22 10:57 被阅读0次
    npm install --save-dev svg-sprite-loader
    vue-cli 2.x :
    在webpack.base.conf.js中配置允许svg依赖
     module: {
        rules: [
          {
            test: /\.svg$/,
            loader: 'svg-sprite-loader',
            include: [resolve('src/assets/icons')], //svg 文件路径
            options: {
              symbolId: 'icon-[name]'
            }
          },
          {
            test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
            loader: 'url-loader',
            exclude: [resolve('src/assets/icons')],
            options: {
              limit: 10000,
              name: utils.assetsPath('img/[name].[hash:7].[ext]')
            }
          }
        ]
      },
    
    vue-cli 3.x 配置
    在根目录新建vue.config.js文件中配置loader
    module.exports = {
      chainWebpack: config => {
        // svg rule loader
        const svgRule = config.module.rule('svg') // 找到svg-loader
        svgRule.uses.clear() // 清除已有的loader, 如果不这样做会添加在此loader之后
        svgRule.exclude.add(/node_modules/) // 正则匹配排除node_modules目录
        svgRule // 添加svg新的loader处理
          .test(/\.svg$/)
          .use('svg-sprite-loader')
          .loader('svg-sprite-loader')
          .options({
            symbolId: 'icon-[name]',
          })
        // 修改images loader 添加svg处理
        const imagesRule = config.module.rule('images')
        imagesRule.exclude.add(resolve('src/assets/icons'))
        config.module
          .rule('images')
          .test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
      }
    }
    
    创建SvgIcon.vue
    <template>
      <svg :class="svgClass" aria-hidden="true">
        <use :xlink:href="iconName"></use>
      </svg>
    </template>
    
    <script>
    export default {
      name: 'svg-icon',
      props: {
        iconClass: {
          type: String,
          required: true
        },
        className: {
          type: String
        }
      },
      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;//此属性为更改svg颜色属性设置
      overflow: hidden;
    }
    </style>
    
    //index.js
    import Vue from 'vue'
    import SvgIcon from '@/components/SvgIcon'
    // 全局注册组件
    Vue.component('svg-icon', SvgIcon)
    // 定义一个加载目录的函数
    const requireAll = requireContext => requireContext.keys().map(requireContext)
    const req = require.context('@/assets/icons', false, /\.svg$/)
    // 加载目录下的所有 svg 文件
    requireAll(req)
    
    在main.js中引入执行,index.js文件
    

    相关文章

      网友评论

          本文标题:vue 使用svg

          本文链接:https://www.haomeiwen.com/subject/bysuhrtx.html