vite 下载入 svg 图标
- 安装插件:vite-plugin-svg-icons:https://www.npmjs.com/package/vite-plugin-svg-icons
npm i vite-plugin-svg-icons -D
- 在
vite.config.js
中配置
import viteSvgIcons from 'vite-plugin-svg-icons'
import path from 'path'
export default () => {
return {
plugins: [
viteSvgIcons({
// Specify the icon folder to be cached
iconDirs: [path.resolve(process.cwd(), 'src/icons')],
// Specify symbolId format
symbolId: 'icon-[dir]-[name]'
})
]
}
}
- 在
main.js
中加入如下代码:
import 'virtual:svg-icons-register'
- 新建 vue 组件:
/src/components/SvgIcon.vue
<template>
<svg :class="svgClass" aria-hidden="true">
<use :href="symbolId" />
</svg>
</template>
<script>
import { defineComponent, computed } from 'vue'
export default defineComponent({
name: 'SvgIcon',
props: {
prefix: {
type: String,
default: 'icon'
},
name: {
type: String,
required: true
},
className: {
type: String,
default: ''
}
},
setup(props) {
const symbolId = computed(() => `#${props.prefix}-${props.name}`)
const svgClass = computed(() => {
if (props.className) {
return `svg-icon ${props.className}`
}
return 'svg-icon'
})
return { symbolId, svgClass }
}
})
</script>
<style scope>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.1em; /* 因icon大小被设置为和字体大小一致,而span等标签的下边缘会和字体的基线对齐,故需设置一个往下的偏移比例,来纠正视觉上的未对齐效果 */
fill: currentColor; /* 定义元素的颜色,currentColor是一个变量,这个变量的值就表示当前元素的color值,如果当前元素未设置color值,则从父元素继承 */
overflow: hidden;
}
</style>
- src 目录下建立 icons 目录存放 svg 图标
# src/icons
- back.svg
- 页面使用
<header>
<SvgIcon name="back" className="back" @click="backHome"></SvgIcon>
<h2 class="title">我的</h2>
</header>
<script>
...
setup() {
const backHome = () => {
router.go(-1)
}
return {
backHome
}
}
</script>
<style lang="scss" scoped>
header {
height: 0.4rem;
background-color: #ccc;
position: relative;
.back {
position: absolute;
left: 0.1rem;
top: 0.1rem;
font-size: 0.18rem;
color: #f60; /* 这里定义图标的颜色 */
}
.title {
margin: 0;
text-align: center;
line-height: 0.4rem;
}
}
</style>