vue3 中使用svg-icon

准备

安装 svg-sprite-loader

npm i svg-sprite-loader@6.0.11

下载 iconfont 并导入项目

  1. 在 assets 目录下新建 icons 目录,在 icons 目录下继续新建 svg 目录(用来存放svg图标)。
  2. 在 svg 目录下新建 user.svg 文件。
  3. iconfont-阿里巴巴矢量图标库官方搜索 user,选择需要的图标,复制 SVG 代码到刚才创建的 user.svg 文件中。

配置 vue.config.js

const { defineConfig } = require('@vue/cli-service')

const path = require('path')
const resolve = (dir) => path.join(__dirname, dir)

module.exports = defineConfig({
  ……,
  chainWebpack (config) {
    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/assets/icons'))  // 存放 svg 目录的目录
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/icons'))  // 存放 svg 目录的目录
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
  }
})

封装使用

封装 svg-icon 组件

在 components 目录下新建 SvgIcon.vue:

<template>
  <svg :class="svgClass" :style="{ width: size + 'px', height: size + 'px', color: color }" aria-hidden="true">
    <use :xlink:href="`#icon-${name}`" />
  </svg>
</template>

<script>
export default {
  name: 'svg-icon',
  props: {
    name: { type: String, required: true },     // svg 图标名称
    className: { type: String, default: '' },   // 指定的类样式
    size: { type: Number, default: 32 },        // 图标尺寸
    color: { type: String, default: "#000" }    // 图标颜色
  },
  computed: {  // 计算属性
    svgClass () {
      if (this.className) {
        return 'svg-icon ' + this.className
      } else {
        return 'svg-icon'
      }
    }
  }
}
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

导入图标

在上面新建的 assets/icons 目录下新建 index.js 文件:

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

在 main.js 文件中导入图标和图标组件:

import '@/assets/icons'  // 导入图标资源
import SvgIcon from '@/components/SvgIcon.vue'// svg component

var app = createApp(App)
app
  .component('svg-icon', SvgIcon)
  .mount('#app')

使用

<svg-icon name="user" color="red" size='48'></svg-icon>
  • 5
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Qanx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值