• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

vue2自定义字体svg图标的使用svg-sprite-loader

武飞扬头像
light多记一点
帮助1


前言

在项目开发中一般都会使用一些组件的字体图标,但是组件中的字体图标有限,所以在项目中一般都会使用自己团队中开发的svg格式的图片,来自定义字体图标去使用。本次项目中使用vue2 element UI。处理svg使用的是svg-sprite-loader


一、安装

安装处理svg封装好的包

npm i svg-sprite-loader --save-dev

二、配置项目文件

1.配置webpack.config.js

文件路径:build文件夹下

学新通

1.1、webpack.base.js整体代码

'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')

function resolve(dir) {
  return path.join(__dirname, '..', dir)
}



module.exports = {
  context: path.resolve(__dirname, '../'),
  entry: {
    app: ['babel-polyfill', './src/main.js']
  },
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'testdev'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
      'static': path.resolve(__dirname, '../static'),
      'assets': path.resolve(__dirname, '../src/assets'),
    }
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test')]
      },
      {
        test: /\.scss$/,
        loaders: ['style', 'css', 'sass']
      },

      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.sass$/,
        loaders: ['style', 'css', 'sass']
      },
        {
            test: /\.svg$/,
            loader: 'svg-sprite-loader',
            include: [resolve('src/icons')],
            options: {
                symbolId: 'icon-[name]'//去掉svg这个图片加载不出来
            }
        },

        {
            test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
            loader: 'url-loader',
            //这个不处理svg图片,因为我们独立拆开让svg-sprite-loader来处理了
            exclude: [resolve('src/icons')],

            options: {
                limit: 10000,
                name: utils.assetsPath('img/[name].[hash:7].[ext]')
            }
        },

    ]
  },
  node: {
    // prevent webpack from injecting useless setImmediate polyfill because Vue
    // source contains it (although only uses it if it's native).
    setImmediate: false,
    // prevent webpack from injecting mocks to Node native modules
    // that does not make sense for the client
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  }
}

学新通

1.2 、其中包含配置svg需要的代码

	{
            test: /\.svg$/,
            loader: 'svg-sprite-loader',
            include: [resolve('src/icons')],
            options: {
                symbolId: 'icon-[name]'//去掉svg这个图片加载不出来
            }
        },

        {
            test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
            loader: 'url-loader',
            //这个不处理svg图片,因为我们独立拆开让svg-sprite-loader来处理了
            exclude: [resolve('src/icons')],

            options: {
                limit: 10000,
                name: utils.assetsPath('img/[name].[hash:7].[ext]')
            }
        },

学新通

2.配置svg文件

在src下新建icons目录,然后svg图片放到svg目录中,和配置文件index.js文件

路径截图如下:
学新通
index.js文件代码如下

import Vue from 'vue'
import SvgIcon from '@/components/common/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)

3.封装svgIcon组件

路径为component目录下

<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: 10rem;
    height: 10rem;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
}
</style>

学新通

4.配置main.js文件

将src下的icons目录整个导入就行了。

import Vue from 'vue';
import App from './App';
import router from './router';
import "babel-polyfill";
import 'nprogress/nprogress.css'
import './permission.js'
import store from './store/index'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
// require('./mock');
//引入svg
import './icons'
import echarts from 'echarts'
Vue.prototype.$echarts = echarts

Vue.use(ElementUI, { size: 'small' })

new Vue({
    el: '#app',
    store,
    router,
    render: h => h(App)
})
学新通

三、使用

改变字体图标的大小可以直接通过style内联样式改变,icon-class直接给svg图片的名字就可以了

正常导入组件就可以使用了。

<svg-icon icon-class="home_san" size="10" style="width: 0.625rem;height: 0.625rem;margin:0 0.2rem"></svg-icon>

四、效果图

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhibefef
系列文章
更多 icon
同类精品
更多 icon
继续加载