前端必知必会,你不知道的前端vue插件

svg-sprite-loader 使用教程

2019-05-27  本文已影响25人  赵永盛

本篇文章是在 vue-cli 脚手架项目环境下讲解

svg-sprite-loader 将加载的 svg 图片拼接成 雪碧图,放到页面中,其它地方通过 <use> 复用

首先在 src 下建立以下目录和文件:
安装和配置 svg-sprite-loader:

安装:

npm i -D svg-sprite-loader

webpack 配置:

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

注意 url-loader 中要将 icons 文件夹排除, 不让 url-loader 处理该文件夹

components 中新建组件 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;
  overflow: hidden;
}
</style>
icons 下面的 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)
入口 main.js 将 index.js 引入:
import '@/icons'
然后 就可以使用了:

前面已经全局注册了,所以可以直接使用

<svg-icon icon-class="eye"></svg-icon>
eye.svg 然后在我们使用的地方,使用了 use 进行复用:

欢迎关注!!!顺便下面点个赞呗~

上一篇 下一篇

猜你喜欢

热点阅读