002 若依管理系统前端vue3讲解 - svg雪碧图

小何hdc 跟着小何学编程 

☉本文由小何整理首发,

版权归本公众号所有,

如有侵犯,请自行删除!

svg雪碧图

安装vite-plugin-svg-icons

pnpm install vite-plugin-svg-icons -D

配置

src\main.js

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'

// svg雪碧图
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'


// 
// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) => {
  return {
    plugins: [
      vue(),
      // 注册所有的svg文件生成svg雪碧图
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), "src/assets/icons/svg")], //svg图片存放的目录
        symbolId: "icon-[name]", // 指定symbolId格式
        svgoOptions: command === 'build' // SVG压缩配置
      })
    ],
    resolve: {
      alias: {
        "@": path.resolve("./src") // 相对路径别名配置,使用 @ 代替 src
      }
    }
  }
})

引入样式

src\main.js

import 'virtual:svg-icons-register'

封装svg组件

<template>
    <svg :class="svgClass" aria-hidden="true">
        <use :xlink:href="iconName" :fill="color" />
    </svg>
</template>

<script setup>
const props = defineProps({
    /**
     * svg 的文件名
     */
    iconClass: {
        type: String,
        required: true
    },
    // svg的class
    className: {
        type: String,
        default: ''
    },
    // svg的颜色
    color: {
        type: String,
        default: ''
    },
})

/**
 * 构建svg的完整名称
 */
const iconName = computed(() => `#icon-${props.iconClass}`);

/**
 * 默认使用 svg-icon 类样式
 *  如果传入 className 在 svg-icon 类样式 追加类样式
 */
const svgClass = computed(() => {
    if (props.className) {
        return `svg-icon ${props.className}`
    }
    return 'svg-icon'
})
</script>

<style scope lang="scss">
/* 
  1em
    将icon大小设置和字体大小一致

  fill 是SVG元素的一种属性
    fill 定义元素的颜色,
    currentColor是一个变量,
    这个变量的值就表示当前元素的color值,
    如果当前元素未设置color值,
    则从父元素继承

  vertical-align
    因icon大小被设置为和字体大小一致,
    而span等标签的下边缘会和字体的基线对齐,
    故需设置一个往下的偏移比例,
    来纠正视觉上的未对齐效果
 */
.svg-icon {
    width: 1em;
    height: 1em;
    position: relative;
    fill: currentColor;
    vertical-align: -2px;
}
</style>

全局注册

src\main.js

import SvgIcon from '@/components/SvgIcon/index.vue'

app.component('svg-icon', SvgIcon)

案例

<template>
   <div class="login">
       <svg-icon icon-class="user"   />
   </div>
</template>

<script setup>
</script>

<style lang="scss" scoped>
.login{
   
   display: flex;
   justify-content: center;
   align-items: center;
   height:100%;
}
</style>
 

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值