使用vue 笔记 svg-sprite-loader篇

终于给搞定了!下面来个总结吧:

1、先在package.json中引入,再执行安装,应注意是项目使用 vue init webpack vue-demo01 创建的而非 vue init webpack-simple vuedemo02。

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

2、webpack.base.conf.js配置中 加入

{

        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')],//排除该目录  其他规则中有svg 需要加入排除

        options: {

          limit: 10000,

          name: utils.assetsPath('img/[name].[hash:7].[ext]')

        }

      }

3、建立组件:src/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/ 放入*.svg文件;src/icons/index.js 

index.js 的代码如下:

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)

export default req


5、全局引入icons:src/main.js 加入代码

import './icons' // icon

6、使用icon:list既是list.svg,再App.vue 中加入代码

<svg-icon icon-class="list" class-name="disabled" />


7、运行项目,就能看到您的图标了!

npm run dev

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容