一、svg的基础知识
1.定义:SVG 是一种绘图技术,SVG 的全名叫可缩放矢量图形(Scalable Vector Graphics);使用 XML 格式定义图像;可伸缩,不失真。
2.ui切图与svg对比
切的图片,页面放大会导致图片放大会变的模糊;如果页面中的图片过多的话会造成有很多请求也就代表页面加载慢。所以基于以上问题我们一般使用svg的矢量图,矢量图一般由设计师提供给前端来转换成字体图标,在项目中使用,优点:1、放大不会模糊 2、只加载一次不会有多余的请求
二、svg在vue项目中使用
1.安装
npm install svg-sprite-loader --save-dev
2. 在vue.config.js文件中进行配置
const path = require('path');
module.exports = {
chainWebpack(config) {
// set svg-sprite-loader
config.module
.rule('svg')
.exclude.add(path.resolve(__dirname, 'src/assets/icons/svg'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(path.resolve(__dirname, 'src/assets/icons/svg'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
}
}
3.所有图标放在src/assets/icons/svg文件夹下,并在src/assets/icons文件夹下新建文件index.js
(1)下载svg图标 官网:iconfont-阿里巴巴矢量图标库
(2)index.js文件
const req = require.context('@/assets/icons/svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
4.封装公共组件:在src/compoments/svgicon下创建SvgIcon.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 lang="scss">
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
5.在main.js文件中全局注册
// svg注册为全局组件
import '@/assets/icons/index.js';
import SvgIcon from '@/components/svgicon/SvgIcon.vue';
Vue.component('svg-icon', SvgIcon);
6.在组件中使用
<template>
<div>
<svg-icon class-name="star-icon" icon-class="star"/>
</div>
</template>
<script>
export default {
}
</script>
<style>
.star-icon {
font-size: 30px;
color: gold;
}
</style>