2020年11月02日(vue中使用svg)


vue中如何使用svg

我使用的是svg-sprite-loader插件

image-20201102102213476

在public同级目录下新建icons文件夹,在分别创建svg文件夹和index.js文件

在封装一个SvgIcon组件

image-20201102102353498

在vue.config.js配置

chainWebpack: config => {
    isProd && config.plugin('optimize-css').tap(([options]) => {
      if (options && options.cssnanoOptions) {
        options.cssnanoOptions.preset[1].svgo = false;
      }
      return [options];
    })
    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
  },

使用时,通过className定义类名

image-20201102102609148

SvgIcon.vue

<template>
    <svg :class="svgClass" aria-hidden="true" v-on="$listeners">
        <use :xlink:href='iconName' />>
    </svg>
</template>

<script>
export default {
    name: 'SvgIcon',
    props: {
        iconClass: {
            type: String,
            require: 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: 1.54666rem;
    height: 1.54666rem;
}
.guide {
    width: 1rem;
    height: 1rem;
}
.laye {
    width: 0.58667rem;
    height: 0.58667rem;
}
.send {
    width: 0.4‬rem;
    height: 0.42666rem;
}
.records {
    width: 0.45333‬rem;
    height: 0.45rem;
}
.shared {
    width: 0.42667rem;
    height: 0.42666rem;
}
.voice {
    width: 0.48rem;
    height: 0.53333rem;
}
.exchange {
    width: 0.42667rem;
    height: 0.48‬rem;
}
.icon-2d, .icon-3d, .retroaction {
    margin-top: -0.2rem;
}
</style>

在src/icons/index.js

import Vue from 'vue';
import SvgIcon from '@/components/SvgIcon';

// 注册全局组件
Vue.component('svg-icon', SvgIcon);

const req = require.context('./svg', false, /\.svg$/);
const requireAll = requireContext => requireContext.keys().map(requireContext);
requireAll(req);

最后在main.js引入

image-20201102102803376


Author: wxy
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source wxy !
  TOC