svg
svg 与 png 对比
1、svg 是矢量图,png 是位图。简单了解:位图会受到分辨率大小的影响,分辨率越高,图片越清晰,而矢量图不会受到分辨率影响
2、svg 由图形和路径组成,png 由像素组成
3、svg 不会因为放大而失真,并且支持透明度和动画,是 XML 编写的代码片段;png 清晰度会随着图片的大小而变化,支持透明度但不支持动画
4、svg 可编辑,适合图形设计、文字设计,png 不可编辑
svg 和 png 图片放大效果
vue中使用svg图
1. 安装依赖
npm install svg-sprite-loader -D
2. vue.config.js 中配置
module.exports = {
chainWebpack: (config) => {
const svgRule = config.module.rule('svg')
svgRule.uses.clear()
svgRule.use('svg-sprite-loader').loader('svg-sprite-loader').options({
symbolId: 'icon-[name]',
})
},
}
3. 创建 SvgIcon 目录,封装 svg 组件,挂在全局
src
SvgIcon
svg
ranking.svg
index.vue
index.js
index.vue
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
export default {
name: 'svgIcon',
props: {
data_iconName: {
type: String,
required: true,
},
className: {
type: String,
default: '',
},
},
computed: {
svgClass() {
//svg 的class
if (this.className) {
return `svg-icon ${this.className}`
} else {
return 'svg-icon'
}
},
iconName() {
//svg xlink-href 指向的文件名
return `#icon-${this.data_iconName}`
},
},
}
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
index.js
import Vue from 'vue'
import svgIcon from './index.vue'
Vue.component('svg-icon', svgIcon) //挂载全局组件
//下面这个是导入svgIcon/svg下的所有svg文件
const requireAll = (requireContext) => requireContext.keys().map(requireContext)
const req = require.context('./svg', false, /.svg$/)
requireAll(req)
4. 页面中使用 svg 组件
<template>
<div>
<div class="img_box">
<img src="../assets/ranking.png" alt="" />
</div>
<div class="img_box">
<svg-icon data_iconName="ranking" class="home_icon" />
</div>
</div>
</template>