vue 使用 svg 小图标

1.首先安装

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

2. 在webpack.base.conf.js中手动添加

module: {
    {
        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. 在src/components下新增一个文件夹 SvgIcon/index.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>        

4. 在src下新增文件夹icons/svg存放svg图
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)

5. 在main.js中引入:

import '@/icons' // icon

6. 重新

npm run dev

7. vue的文件中就可以用啦!!  界面使用 如:

<svg-icon icon-class="userName" /> //userName是svg图的命名

  



猜你喜欢

转载自www.cnblogs.com/Galina/p/9224456.html