zoukankan      html  css  js  c++  java
  • vue-svg使用和组件封装

    1.安装处理svg文件的loader

    npm install svg-sprite-loader -D

    通过vue-cli脚手架创建的项目默认情况下会使用 url-loader 对svg进行处理,所以需要处理下:

    vue版本2之前处理如下:修改webpack.base.conf.js配置

      {
        test: /.svg$/,
        loader: 'svg-sprite-loader',
        include: [resolve('src/assets/icons')], // include => 只处理指定的文件夹下的文件
        options: {
            symbolId: 'icon-[name]'
        }
      },
      {
        test: /.(png|jpe?g|gif|svg)(?.*)?$/,
        loader: 'url-loader',
        exclude: [resolve('src/assets/icons')], // exclude => 不处理指定的文件夹下的文件
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      }

    vue3版本及以上:在vue.config.js文件中添加以下配置

    'use strict'
    const path = require('path')
    function resolve(dir) {
      return path.join(__dirname, dir)
    }
    
    module.exports = {
     // 处理运行时版本报错 runtimeCompiler:
    true, chainWebpack(config) { // set svg-sprite-loader config.module .rule('svg') .exclude.add(resolve('src/assets/icons')) .end() config.module .rule('icons') .test(/.svg$/) .include.add(resolve('src/assets/icons')) .end() .use('svg-sprite-loader') .loader('svg-sprite-loader') .options({ symbolId: 'icon-[name]' }) .end() config .when(process.env.NODE_ENV !== 'development', config => { config .plugin('ScriptExtHtmlWebpackPlugin') .after('html') .use('script-ext-html-webpack-plugin', [{ // `runtime` must same as runtimeChunk name. default is `runtime` inline: /runtime..*.js$/ }]) .end() config .optimization.splitChunks({ chunks: 'all', cacheGroups: { libs: { name: 'chunk-libs', test: /[\/]node_modules[\/]/, priority: 10, chunks: 'initial' // only package third parties that are initially dependent }, elementUI: { name: 'chunk-elementUI', // split elementUI into a single package priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app test: /[\/]node_modules[\/]_?element-ui(.*)/ // in order to adapt to cnpm }, commons: { name: 'chunk-commons', test: resolve('src/components'), // can customize your rules minChunks: 3, // minimum common number priority: 5, reuseExistingChunk: true } } }) config.optimization.runtimeChunk('single'), { from: path.resolve(__dirname, './public/robots.txt'), //防爬虫文件 to: './', //到根目录下 } } ) } }

    2. 存放svg文件

    src-->assets-->icons-->svg

     同级目录下创建index.js和requireIcons.js,用于导出svg图片的处理

    index文件:

    import Vue from 'vue'
    import SvgIcon from '@/components/SvgIcon.vue'
    
    Vue.component('svg-icon', SvgIcon)
    
    const requireAll = requireContext => requireContext.keys().map(requireContext)
    const req = require.context('./svg', false, /.svg$/)
    requireAll(req)

    requireIcons.js文件:

      const req = require.context('./svg', false, /.svg$/)
      const requireAll = requireContext => requireContext.keys()
      
      const re = /./(.*).svg/
      const icons = requireAll(req).map(i => {
        return i.match(re)[1]
      })
      export default icons

    组件封装:

    src-->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>
    .svg-icon {
           1em;
          height: 1em;
          vertical-align: -0.15em;
          fill: currentColor;
          overflow: hidden;
      }
    </style>

    使用:

    1.main.js中

    // 模块仅为副作用(中性词、无贬义含义)而导入,而不是导入模块中的任何内容,
    // 这将运行模块中的全局代码,但实际上不导入任何值
    import './assets/icons/index'

    2.需要使用的地方

    <template>
      <div id="app">
       <span class="svg-container svg-container_login"> <svg-icon icon-class="user" /> </span> <div class="svg-container"> <svg-icon icon-class="password"></svg-icon> </div> <div class="svg-container"> <svg-icon icon-class="404"></svg-icon> </div> <div class="icon-list"> <div v-for="(item, index) in iconList" :key="index"> <svg-icon :icon-class="item" style="height: 30px; 16px;color: purple;" /> <span>{{ item }}</span> </div> </div> </div> </template> <script> import icons from './assets/icons/requireIcons.js' export default { name: 'App', data () { return { iconList: icons } } } </script> <style> .svg-container { font-size: 40px; color: blue; } .icon-list { height: 200px; overflow-y: scroll; } </style>

    单独使用某个图标:

    <svg-icon icon-class="404"></svg-icon>

    遍历展示所有图标:

    <div v-for="(item, index) in iconList" :key="index">
        <svg-icon :icon-class="item" style="height: 30px; 16px;color: purple;" />
        <span>{{ item }}</span>
     </div>

    修改图标颜色:

    .svg-container {
          font-size: 40px;
          color: blue;
      }

    完整项目demo:

    https://github.com/lily-mengbm/Web-page-template/tree/master/demo_svg_v4

  • 相关阅读:
    mybatis-plus代码生成模板
    Flask_APScheduler的简单使用
    Linux 配置mysql 远程连接
    ubuntu19.04 安装mysql,没有初始密码,重设初始密码
    ubuntu19.04 配置远程连接ssh
    python3 win 建立虚拟环境(virtualenv)
    python property(不动产)方法
    python,装饰器带参数,原理
    利用python装饰器为字符串添加,HTML标签
    python pymysql 基本使用
  • 原文地址:https://www.cnblogs.com/lilililiwang/p/14913779.html
Copyright © 2011-2022 走看看